Sub topic 12
Slice objects and slice.indices()
This chapter assumes you can index and slice strings with start, stop and step, know that out-of-range slice bounds are clamped, and can read a short try/except block. Here you learn what Python builds when it sees s[a:b:c], how to store that object, and how to ask it for concrete numbers.
What a slice expression really is
When you write s[-3:], Python builds a slice object from the values you typed and passes it to the string. The expression is shorthand for s[slice(-3, None)]. An omitted bound becomes None.
The built-in slice(start, stop, step) accepts the same three values. If you pass a single argument, it is the stop value. So slice(3) means [:3].
| Slice syntax | Equivalent slice object |
|---|---|
| `s[2:5]` | `slice(2, 5)` |
| `s[:3]` | `slice(3)` or `slice(None, 3)` |
| `s[-3:]` | `slice(-3, None)` |
| `s[::-1]` | `slice(None, None, -1)` |
Storing and reusing a slice
A slice object is a value, so you can give it a name and apply it to several strings. This helps when the same position rule applies to many pieces of text, such as the last three characters of each item.
s = "Python"
last_three = slice(-3, None)
print(s[last_three])
print("Slicing"[last_three])
print(last_three.indices(len(s)))
print(slice(None, None, -1).indices(len(s)))The first line prints hon, and the second prints ing. The last two lines show indices(), which is covered next.
Resolving a slice with slice.indices()
A slice object does not know how long the string is, so slice(-3, None) is only a description. The method indices(length) applies the length and returns a tuple (start, stop, step) of concrete integers. It applies three rules:
- Negative bounds are shifted by the length.
Nonebounds are replaced by the default for the step's direction.- Out-of-range bounds are clamped to the valid range.
For a string of length 6, slice(-3, None).indices(6) returns (3, 6, 1). These numbers can be passed to range() to list the positions the slice would visit.
s = "Python"
sl = slice(-3, None)
start, stop, step = sl.indices(len(s))
print(start, stop, step)
print(list(range(start, stop, step)))
print([s[i] for i in range(start, stop, step)])This prints 3 6 1, then [3, 4, 5], then ['h', 'o', 'n'].
For a negative step, the defaults flip. slice(None, None, -1).indices(6) returns (5, -1, -1). The stop of -1 here is a real number for range(), not "the last character". It means "stop before index 0 is passed", which is why range(5, -1, -1) includes index 0. Do not use that stop value as a slice bound. s[5:-1:-1] would be read as a slice that stops at the last character, and it returns an empty string.
s = "Python"
print(repr(s[5:-1:-1]))
print(s[::-1])
print(list(range(5, -1, -1)))Seeing the clamping rule in numbers
Chapter material on out-of-range slices said that bounds are clamped. indices() shows exactly how.
sl = slice(2, 100)
print(sl.indices(6))
print(sl.indices(3))
print(slice(-100, 2).indices(6))The output is (2, 6, 1), then (2, 3, 1), then (0, 2, 1). The stop of 100 is cut down to the length, and -100 is cut up to 0. The same slice object gives different concrete numbers for strings of different lengths.
Common mistakes
- Passing one argument and expecting it to be the start.
slice(2)means stop at 2, not start at 2. Useslice(2, None)for[2:]. - Calling
indices()without a length. It requires one integer argument and raisesTypeErrorotherwise. - Reusing the stop value from
indices()as a slice bound. The returned numbers suitrange(), and a-1stop does not behave the same way in a slice. - Expecting a step of
0to work.slice(None, None, 0).indices(6)raisesValueError, as doess[::0].
Exercise
What does slice(1, 100, 2).indices(6) return, and which characters does "Python"[slice(1, 100, 2)] give?
Show answer
It returns (1, 6, 2), because the stop of 100 is clamped to the length 6. The positions are 1, 3 and 5, so the result is 'yhn'.
Exercise
Write a line using slice and indices() that prints the positions visited by "abcdefghij"[7:2:-2].
Show answer
print(list(range(*slice(7, 2, -2).indices(10)))) prints [7, 5, 3], so the characters are 'h', 'f' and 'd', giving 'hfd'.