Sub topic 8
Skipping characters with a step
This chapter assumes you can already slice with start and stop, including negative indexes and omitted bounds. It adds the third part of the slice syntax, the step.
The third value in a slice
A full slice has the form s[start:stop:step]. The step is the distance between one chosen index and the next. The default step is 1, which takes every character in the range.
s = "abcdefghij"
print(s[::2])
print(s[1::2])
print(s[::-1])
print(s[7:2:-2])This prints:
acegi
bdfhj
jihgfedcba
hfds[::2]starts at index 0 and takes every second character: indexes 0, 2, 4, 6, 8.s[1::2]starts at index 1 and takes indexes 1, 3, 5, 7, 9.s[::-1]uses a negative step, so it walks backward from the end. The next chapter covers this in detail.s[7:2:-2]starts at index 7 and moves back by 2 until it reaches index 2. It takes indexes 7, 5 and 3, which areh,fandd.
How Python picks the indexes
For a positive step, Python begins at start, adds the step each time, and stops before it reaches stop. As with plain slices, stop is never included.
s = "abcdefghij"
print(s[1:9:3])
print(s[2:8:3])The first line prints beh (indexes 1, 4, 7). The second prints cf (indexes 2 and 5, since index 8 equals stop and is excluded).
The result length for a positive step is the number of values in the range, rounded up: ceil((stop - start) / step). For s[1:9:3] that is ceil(8 / 3), which is 3.
The defaults depend on the sign of the step:
| Step | Default start | Default stop |
|---|---|---|
| Positive | Beginning of the string | End of the string |
| Negative | Last character | Before the first character |
This is why s[::-1] covers the whole string. Both bounds default to the far ends, in the direction of travel.
Common errors
A step of zero is not allowed. Python can't move forward by zero, so it raises an error instead of looping.
s = "abcdefghij"
try:
s[::0]
except ValueError as e:
print(e)This prints slice step cannot be zero.
The second common mistake is a direction that doesn't match the step. When the step is positive, start must be to the left of stop. When it is negative, start must be to the right. If not, the result is an empty string and no error is raised, just as with out-of-range slices.
s = "abcdefghij"
print(repr(s[2:7:-1]))
print(repr(s[7:2:1]))Both lines print ''. If you get an unexpected empty result, check whether the step's sign matches the direction from start to stop.
Why a step is useful
Stepped slices let you split interleaved data without a loop. For example, a string that alternates two kinds of values can be separated with s[0::2] and s[1::2]. The two results together contain every character exactly once. Because slicing returns a new string, the original s is not changed.
Exercise
Given s = "abcdefghij", what do s[2:9:3] and s[8:1:-3] return? List the indexes each one uses.
Show answer
s[2:9:3] uses indexes 2, 5 and 8, so it returns "cfi". s[8:1:-3] uses indexes 8, 5 and 2 (the next one, -1, is before stop 1 in the walk and is not reached), so it returns "ifc".