Page 77 - Python Basics: A Practical Introduction to Python 3
P. 77
4.2. Concatenation, Indexing, and Slicing
Note
The empty string is called empty because it doesn’t contain any
characters. You can create it by writing two quotation marks
with nothing between them:
empty_string = ""
A string with anything in it—even a space—is not empty. All the
following strings are non-empty:
non_empty_string1 = " "
non_empty_string2 = " "
non_empty_string3 = " "
Even though these strings don’t contain any visible characters,
they are non-empty because they do contain spaces.
You can use negative numbers in slices. The rules for slices with nega-
tive numbers are exactly the same as the rules for slices with positive
numbers. It helps to visualize the string as slots with the boundaries
labeled with negative numbers:
| f | i | g | | p | i | e |
-7 -6 -5 -4 -3 -2 -1
Just like before, the slice [x:y] returns the substring starting at index
x and going up to but not including y. For instance, the slice [-7:-4]
returns the first three letters of the string "fig pie":
>>> flavor[-7:-4]
'fig'
Notice, however, that the rightmost boundary of the string does not
have a negative index. The logical choice for that boundary would
seem to be the number 0, but that doesn’t work.
76