Python String Indexing and Slicing
Get One Character with a String Index
A string is a row of characters, and every character has a position number called its index. Put the index in square brackets after the string to get that one character: name[0].
Think of it like the seats in a cinema row. Every seat has a number, so you can walk straight to seat 3 without checking the others.
name = "Sunny"
print(name[0])
print(name[1])
print(name[4])S u y
It works exactly like the list indexes from chapter 9, because a string is a sequence too: a sequence of characters.
| Character | Index | Negative index |
|---|---|---|
| S | 0 | -5 |
| u | 1 | -4 |
| n | 2 | -3 |
| n | 3 | -2 |
| y | 4 | -1 |
The rules
- The first character is at index 0, not 1.
- The last character is at index
len(name) - 1. - Negative indexes count from the end:
-1is the last character,-2the one before it. - Spaces and punctuation are characters too, so they have an index like everything else.
city = "New York"
print(city[-1])
print(city[4])
print(city[len(city) - 1])k Y k
city[4] is Y because the space at index 3 counts. And -1 is a short way to write len(city) - 1.
Avoid: an index past the end
name = "Sunny"
print(name[5])IndexError: string index out of range
Don't be scared of this error! It's saying: "There's no character at that position." "Sunny" has 5 characters, so the last index is 4.
Common beginner doubt: "Why does counting start at 0?" Read the index as "how many steps from the start". The first character is 0 steps away, the second is 1 step away.
text[0]is the first character andtext[-1]is the last.