Sub topic 11
Indexing and Slicing Strings
This chapter assumes you can run Python code, use print(), and know that a string is a sequence of characters. It covers how to pick out single characters (indexing) and pieces of a string (slicing), and the errors that come up most often.
Indexing
A string is an ordered sequence. Each character has a position, called an index. Indexes start at 0 from the left. Negative indexes count from the right, so -1 is the last character.
s = "Python"
print(s[0])
print(s[-1])This prints P and then n. Indexing returns a new one-character string. Python has no separate character type.
Using an index outside the string raises IndexError. For a string of length n, valid indexes run from -n to n - 1.
Slicing
A slice has the form s[start:stop:step]. It includes start and stops before stop. Any part can be left out.
s = "Python"
print(s[1:4])
print(s[:2])
print(s[3:])
print(s[::2])
print(s[::-1])The output is yth, Py, hon, Pto, and nohtyP. A negative step walks backward, so s[::-1] reverses the string.
Because the stop index is excluded, s[:k] + s[k:] always equals s. The length of s[a:b] is b - a when both are in range and a < b.
| Slice | Result | Meaning |
|---|---|---|
| `s[1:4]` | `yth` | From index 1 up to, not including, 4 |
| `s[:2]` | `Py` | First two characters |
| `s[-3:]` | `hon` | Last three characters |
| `s[::-1]` | `nohtyP` | Whole string, reversed |
Strings are immutable
Indexing and slicing read from a string. They cannot change it. Assigning to an index raises TypeError. To get a changed string, build a new one.
s = "Python"
try:
s[0] = "J"
except TypeError as e:
print("TypeError:", e)
print("J" + s[1:])The last line prints Jython. The original s is unchanged.
Common errors
- Off-by-one at the stop index.
s[1:4]has three characters, not four. Remember that the stop is excluded. - Using 1 as the first index. The first character is
s[0]. IndexErroron empty strings.""[0]fails, but""[:1]returns"". Use a slice when the string might be empty.- Confusing the sign of the step. With a negative step,
startshould be larger thanstop.s[1:4:-1]is empty, whiles[4:1:-1]givesoht. - Expecting bytes. Indexes count characters (code points), not bytes.
"café"[3]isé.
Exercise
Given s = "programming", write one expression that returns the last four characters, and say what s[2:8:2] returns.
Show answer
s[-4:] returns "ming". The slice s[2:8:2] takes indexes 2, 4, and 6, which are o, r, and a, so it returns "ora".
Exercise
Why does "abc"[3] raise an error while "abc"[3:] does not?
Show answer
Indexing needs an existing position, and the valid indexes for a three-character string are 0 to 2 (or -3 to -1), so 3 raises IndexError. Slicing clips its bounds, so "abc"[3:] is an empty string.