Sub topic 8
Skipping characters with a step
What you need first
This chapter assumes you can run Python code and use print() and len(). It also assumes you can read a simple try/except block. You should already know zero-based indexes, negative indexes, and slices of the form s[start:stop]. Here you add the third value of a slice, the step, which controls how far Python moves between the characters it picks.
The third value in a slice
A full slice has three parts separated by colons:
s[start:stop:step]Python starts at start. It takes the character there, moves forward by step positions, and takes that character. It repeats this while the index is still before stop. As in a two-part slice, stop is excluded.
With no step, Python moves one position at a time. That is why s[2:5] and s[2:5:1] give the same result.
s = "abcdefghij"
print(s[::2])
print(s[1::2])
print(s[::3])
print(s[2:8:3])The output is:
acegi
bdfhj
adgj
cfThe first line uses start=0 and stop=10 by default, so it visits indexes 0, 2, 4, 6 and 8. The second line begins at index 1, so it visits 1, 3, 5, 7 and 9. The last line begins at index 2 and moves by 3. It takes index 2 and index 5, then stops because index 8 is not less than the stop value 8.
The choice of start matters when the step is larger than 1. The step only decides the spacing. The start decides which characters in the string line up with that spacing.
The walk, step by step
The rule for a positive step can be written as a loop. This is a mental model of what Python does. The real work happens in C, but the result is the same.
The result has no characters when start is already at or past stop. This is the same empty-result behavior you saw with ordinary slices. For a positive step, the number of characters in the result is the length of the range divided by the step, rounded up. For example, s[2:8:3] covers 6 positions, and 6 divided by 3 is exactly 2.
A reference table
This table uses s = "abcdefghij", where a is at index 0 and j is at index 9.
| Expression | Indexes visited | Result |
|---|---|---|
| `s[::2]` | 0, 2, 4, 6, 8 | `'acegi'` |
| `s[1::2]` | 1, 3, 5, 7, 9 | `'bdfhj'` |
| `s[::3]` | 0, 3, 6, 9 | `'adgj'` |
| `s[2:8:3]` | 2, 5 | `'cf'` |
| `s[2::3]` | 2, 5, 8 | `'cfi'` |
| `s[-3::2]` | 7, 9 | `'hj'` |
| `s[4:4:2]` | none | `''` |
| `s[::20]` | 0 | `'a'` |
The last row shows that a large step is not an error. Python takes the first character, jumps past the end, and stops.
Negative start and stop values work as before. Python adds the length of the string to a negative bound, so -3 becomes 7 in a string of length 10. Then it walks forward by the step.
Picking every nth character
To take every nth character starting with the first, use s[::n]. To take the nth, 2nth, 3nth character and so on, start at index n - 1:
s = "abcdefghij"
n = 3
print(s[::n])
print(s[n - 1::n])The first slice prints adgj, which is characters 1, 4, 7 and 10 when counting from one. The second prints cfi, which is characters 3, 6 and 9.
Counting from one and indexing from zero is a common source of off-by-one mistakes. Write down the first index you want, then use it as the start.
Splitting interleaved data
Two slices with the same step and different starts split a string that alternates between two kinds of data. A step of 2 with starts 0 and 1 separates the even and odd positions:
def deinterleave(text):
return text[::2], text[1::2]
letters, digits = deinterleave("a1b2c3")
print(letters)
print(digits)This prints abc and then 123. Together the two slices use every index exactly once, so no character is lost or counted twice.
Defaults depend on the direction
When you leave out start or stop with a positive step, Python uses the beginning and the end of the string. The defaults change when the step is negative, because the walk runs from right to left. In that case, an omitted start means the last character, and an omitted stop means "go all the way past the first character".
This chapter only previews negative steps. The next chapter covers reversing a string in detail. The example below shows that the same rules apply to a step of -2, but in the other direction:
s = "abcdefghij"
print(s[::-1])
print(s[7:2:-2])The first line prints the reversed string jihgfedcba. The second starts at index 7 and moves left by 2. It visits indexes 7, 5 and 3 and stops before index 2, so it prints hfd.
Two things follow for a negative step. First, start should be to the right of stop. Second, the stop index is still excluded, so index 2 is not taken. If the direction does not match the step, the result is empty:
s = "abcdefghij"
print(repr(s[2:7:-1]))
print(repr(s[7:2]))Both lines print ''. In the first, Python walks left from index 2 and is already past index 7. In the second, the default step of 1 walks right from index 7 and is already past index 2. When a slice comes out empty, check that the direction of the step matches the order of start and stop.
Out-of-range bounds still clamp
As with two-part slices, bounds outside the string do not raise an error. Python clamps them to the valid range first and then applies the step:
s = "abcdefghij"
print(s[3:100:4])
print(s[-100:4:2])The first line prints dh. The stop bound of 100 becomes 10, and the indexes visited are 3 and 7. The next index would be 11, which is beyond the end. The second line prints ac. The start bound of -100 becomes 0, and the indexes visited are 0 and 2.
A single index does not clamp. s[100] raises IndexError, while s[::100] returns a one-character string.
Invalid steps
A step must be an integer, and it cannot be zero. A zero step would never advance, so Python rejects it:
s = "abcdefghij"
for bad_step in (0, 1.5):
try:
s[::bad_step]
except (ValueError, TypeError) as e:
print(type(e).__name__)This prints ValueError for the zero step and TypeError for the float.
Checking a slice against range()
A step slice visits the same indexes as a range with the same three values, once the bounds are clamped. The slice.indices() method does that clamping and gives you the concrete numbers. You will meet slice objects properly in a later chapter, but the idea is useful here as a way to verify your predictions:
s = "abcdefghij"
sl = slice(2, 100, 3)
start, stop, step = sl.indices(len(s))
print((start, stop, step))
print(list(range(start, stop, step)))
print(s[sl])This prints (2, 10, 3), then [2, 5, 8], then cfi. The 100 became 10, and the list shows exactly which positions were taken. When a slice surprises you, printing list(range(*sl.indices(len(s)))) shows which indexes it used.
Strings stay immutable
A slice with a step builds a new string. It never changes the original. You cannot assign to a stepped slice either, because a str has no item assignment at all:
s = "abcdefghij"
try:
s[::2] = "XXXXX"
except TypeError as e:
print(e)The message says that a str object does not support item assignment. To replace every second character, build the result from the pieces you want. One way is to take both interleaved halves and join them back together:
s = "abcdefghij"
evens = "XXXXX"
odds = s[1::2]
result = "".join(a + b for a, b in zip(evens, odds))
print(result)This prints XbXdXfXhXj. The new string has the same length as the original, but it is a separate object.
Each stepped slice also copies the characters it selects. The cost grows with the length of the result, not with the step size. s[::1000] on a very long string touches few characters. s[::2] copies half of them.
Code points, not visible characters
A step moves over code points. A visible character made of more than one code point can be split, or its parts can be separated from the base letter. The word "café" below is written with a plain e followed by a combining accent (U+0301), which makes five code points:
s = "cafe\u0301"
print(len(s))
print(ascii(s[::2]))This prints 5 and then 'cf\u0301'. The step took indexes 0, 2 and 4: the c, the f and the combining accent. The accent now sits after the f. The result is cf with an accent on the f, which is not text anyone meant to write. Stepping over text that may contain combining marks can produce results like this, so be careful with it when the text comes from real user input.
Common mistakes
- Forgetting that
stopis excluded, sos[0:10:2]on a 10-character string stops before index 10 and never reaches a character at that position. - Expecting
s[::2]to include the last character. It does only when the length is odd, since the last index is then even. - Using a negative step with a
startthat is left ofstopand getting an empty string. - Passing a step of 0, or a non-integer step such as
2.0. - Assuming stepping separates visible characters. It separates code points.
Exercise
For s = "abcdefghij", what does s[3:12:4] return, and which indexes does it visit?
Show answer
It returns 'dh'. The stop bound 12 is clamped to 10. Python visits index 3 ('d') and index 7 ('h'). The next index would be 11, which is not less than 10, so the walk ends.
Exercise
A string holds pairs of characters in the form "k1k2k3" where letters are keys and digits are values, as in "a1b2c3". Write one expression that returns only the keys, one that returns only the values, and one that returns the characters at every third position starting from index 2 for the string "abcdefghij".
Show answer
Keys: text[::2], which gives 'abc'. Values: text[1::2], which gives '123'. Every third character starting at index 2: s[2::3], which gives 'cfi' for "abcdefghij".