youtube facebook twitter gmail pinterest

Strings In Python

Besides numbers, Python can also manipulate strings, which can be expressed in several ways. They can be enclosed in single quotes ('...') or double quotes ("...") with the same result [2]. \ can be used to escape quotes:

print('Hello World')   #Single Quotes
print("Hello World")  #double quotes

print('the number is:',53)   #can do this
print('the number is:'+53)   #cannot do this

In the interactive interpreter, the output string is enclosed in quotes and special characters are escaped with backslashes. While this might sometimes look different from the input (the enclosing quotes could change), the two strings are equivalent. The string is enclosed in double quotes if the string contains a single quote and no double quotes, otherwise it is enclosed in single quotes. The print() function produces a more readable output, by omitting the enclosing quotes and by printing escaped and special characters:
>>> word = ‘Tutorialslot'
>>> word[0]   # character in position 0
>>> word[5]   # character in position 5
Indices may also be negative numbers, to start counting from the right:

>>>len(word) #word length
>>> word[-1]   # last character
>>> word[-2]   # second-last character
>>> word[-12]
Note that since -0 is the same as 0, negative indices start from -1.

In addition to indexing, slicing is also supported. While indexing is used to obtain individual characters, slicing allows you to obtain substring:

>>> word[0:2]   # characters from position 0 (included) to 2 (excluded)
>>> word[2:5]  # characters from position 2 (included) to 5 (excluded)
Note how the start is always included, and the end always excluded. This makes sure that s[:i] + s[i:] is always equal to s:

>>> word[:2] + word[2:]
>>> word[:4] + word[4:]
Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

>>> word[:2]   # character from the beginning to position 2 (excluded)
>>> word[11:]   # characters from position 4 (included) to the end
>>> word[-2:]   # characters from the second-last (included) to the end
One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n, for example:

| T | u | t | o | r | i | a | l | s | l | o | t |
0 1 2 3 4 5 6 7 8 9 10 11 12
-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0
>>> print('C:\tutorialslot\name')  # here \n means newline!
>>> print(r'C:\tutorialslot\name')   # note the r before the quote

Advertisement Powered By Google Adsense


Share on whatsapp


python python tutorial learn python learning python python code learning java python language python documentation python tutor python basics python download python online python for dummies how to learn python