DEVASC 200-901 - Python Strings

*This is a summary from the DEVASC 200-901 Official Cert Guide.

**The examples are formatted so that the result appears on the same line after >>>.

The string data type is a sequence of characters inside quotes. You can use single quotes (' ') or double quotes (" "). A string can also include numbers and other characters. However, some characters in Python strings have special use cases.

Example: Create a string.

>>> word = 'Python'

In Python, you don't have to explicitly specify the data type, when you assign a value to an object. Python automatically recognizes the type from the value.

A string is just a list of characters in a certain order that Python keeps track of. Strings are indexed starting from 0. You can retrieve any character in the string by referencing its index.

Example: Find the first character in the string.

>>> word[0] >>> 'P'

You can also pull ranges of characters by using a colon (:). The format is [x:y], where x is the beginning of the slice and y determines the end. Note that the second number (y) is considered "up to but not including", so the last character to be retrieved is the one before the specified index. You can also leave out the start index (to print from the start of the string) or leave out the end index (to print out the end of the string).

Example: Find the characters from index 1 to 4 ("up to but not including").

>>> word[1:4] >>> 'yth'

You can also use negative numbers to indicate the index. If you use a negative number, you start from the end at position -1.

Example: Find the last character in the string.

>>> word[-1] >>>'n'

You can perform math operations on strings as well. The plus (+) operator is used to add or concatenate two strings together.

>>> 'Python' + 'Space' >>> 'PythonSpace'

Multiplication (*) works as well.

>>> 'Fun! ' * 3 >>> 'Fun! Fun! Fun! '

There are many built-in methods in Python that allow you to manipulate the string in different ways.

Example: Convert all characters in the string to upper case.

>>> word.upper() >>> 'PYTHON'

See: https://docs.python.org/3/library/stdtypes.html (String Methods)

Watch my YouTube video: DEVASC - Introduction to Python Strings

#Cisco #DevNet #DEVASC

要查看或添加评论,请登录

Riikka Sihvonen的更多文章

社区洞察

其他会员也浏览了