String Indexing
We sometimes need to access individual characters in a string. The characters in a string can be located using their index value, which represents their position in the string. Enclosing the index in square brackets will select a single character from a string:
[index number]
To get a character at position i in string str, use square brackets str[i].
- characters are indexed from left to right, starting from the position
0, not1! - indexing: the positions are also named from right to left using negative numbers, where
-1is the rightmost index and decreases by one as you move left. - blank spaces are also considered characters.
Slicing Strings
str[start: end: step] returns a segment, or slice, of the string str. It selects the part of the string from indices start to index end (excluding the number end itself), separating the values by step. The step is 1 by default if you do not include it.
food = 'blueberry muffin'
m = food[2]
t = food[-2]
print (m, t) # u i
n = food[4:9]
print(n) # berry (slice from indices 4 to 9, excluding 9)
r = food[4:]
print(r) # berry muffin (slice from index 4 to the end)
s = food[:4]
print(s) # blue (slice from the beginning to index 4)
To understand how slicing works, think of an index as a pointer between each character in a string:
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1 0
0 is before the first element but also after the last element, as if the string wraps around. [start:end] includes everything between the two indices.