Sub topic 9
Negative steps and reversing a string
This chapter assumes you can read s[start:stop] slices with positive and negative indexes, you know that stop is excluded, and you have seen the step value in s[start:stop:step]. Here you will see what changes when the step is negative. You will also learn the defaults that make s[::-1] work, the mistakes people make with stop, and where reversal by slicing breaks down.
What a negative step does
A positive step walks from start toward the end of the string. A negative step walks from start toward the beginning. Python begins at start and moves by step after each character. It stops before it reaches or passes stop.
s = "Python"
print(s[4:1:-1])
print(s[5:0:-1])
print(s[-1:-4:-1])
print(s[::-2])The output is:
oht
nohty
noh
nhyFor s[4:1:-1], Python visits indexes 4, 3 and 2. These are o, h and t. It stops before index 1, because stop is still excluded when the step is negative. For s[::-2], the visited indexes are 5, 3 and 1, which give n, h and y.
With a negative step, start must be the larger index and stop the smaller one. The first character you get is the one at start. The slice never includes stop.
Defaults depend on the sign of the step
Leaving out start or stop does not always mean "the beginning" or "the end". The defaults depend on the direction of travel.
| Step | Default `start` | Default `stop` |
|---|---|---|
| positive (or omitted) | first character (index 0) | past the last character |
| negative | last character (index `len(s) - 1`) | before the first character |
This is why s[::-1] reverses the whole string. The start defaults to the last character, the stop defaults to the position before the first one, and the step moves one character backward each time.
You can leave out one bound and keep the other:
s = "Python"
print(s[5::-1])
print(s[:2:-1])
print(s[2::-1])The output is:
nohtyP
noh
tyPs[5::-1] starts at index 5 and runs to the beginning. s[:2:-1] starts at the default last index, which is 5, and stops before index 2, so it returns indexes 5, 4 and 3. s[2::-1] returns indexes 2, 1 and 0.
Reversing a string
The standard way to reverse a string by slicing is s[::-1]. It returns a new string and leaves the original unchanged.
s = "abcdefghij"
print(s[::-1])
print(s[::-3])
print(s[7:2:-2])The output is:
jihgfedcba
jgda
hfds[::-3] reverses the string and keeps every third character, starting from the last one. That visits indexes 9, 6, 3 and 0. s[7:2:-2] visits indexes 7, 5 and 3, which give h, f and d.
Reversing is the basis of the palindrome check from earlier in this tutorial:
def is_palindrome(text):
cleaned = text.lower()
return cleaned == cleaned[::-1]
print(is_palindrome("Level"))
print(is_palindrome("Python"))The output is True and then False.
Seeing which indexes a slice visits
When a slice surprises you, ask Python which indexes it will use. A slice object has an indices(length) method that returns concrete (start, stop, step) numbers. You can pass them to range to list the positions.
s = "Python"
for sl in (slice(None, None, -1), slice(None, None, -2), slice(2, None, -1), slice(4, 1, -1)):
start, stop, step = sl.indices(len(s))
print(sl, "->", (start, stop, step), list(range(start, stop, step)))The output is:
slice(None, None, -1) -> (5, -1, -1) [5, 4, 3, 2, 1, 0]
slice(None, None, -2) -> (5, -1, -2) [5, 3, 1]
slice(2, None, -1) -> (2, -1, -1) [2, 1, 0]
slice(4, 1, -1) -> (4, 1, -1) [4, 3, 2]Notice that the default stop for a negative step shows up as -1 in this output. Here -1 is a plain number for range, meaning "stop before index 0". It is not the "last character" index. This leads to the most common mistake with negative steps.
The stop value `-1` trap
In a slice expression, a negative stop is counted from the end, so -1 means the last character. That is different from the -1 above. If you write -1 as the stop of a reversed slice, you ask Python to stop before the last character, which is where you probably started.
s = "Python"
print(repr(s[5:-1:-1]))
print(repr(s[5:-7:-1]))The output is:
''
'nohtyP's[5:-1:-1] starts at index 5. The stop -1 is converted to index 5 as well, so the start and stop are the same position and nothing is returned. To reach index 0 with an explicit stop, use a negative number that is further left than the first character. For a string of length 6, -7 works because it is clamped to "before index 0". Writing that by hand is fragile, so omit stop instead. The shorter forms s[::-1] and s[5::-1] express the same intent and do not depend on the length.
Direction mismatches give empty strings
As with positive steps, a slice whose direction does not match the sign of the step is not an error. It is empty.
s = "Python"
print(repr(s[2:5:-1]))
print(repr(s[5:2]))
print(repr(s[3:3:-1]))The output is three empty strings:
''
''
''s[2:5:-1] starts at 2 and would need to move backward to reach 5, which is ahead of it. s[5:2] has a positive step but a start that is greater than the stop. s[3:3:-1] has equal bounds, so nothing lies between them. If you swap start and stop while moving from a positive step to a negative one, the result is empty and Python does not warn you. Print list(range(*sl.indices(len(s)))) when you need to check.
Out-of-range bounds are clamped, as they are for positive steps:
s = "Python"
print(s[100::-1])
print(s[:-100:-1])The output is nohtyP twice. A start of 100 is clamped to the last index. A stop of -100 is clamped to "before the first character".
A step of zero is an error
A step of zero would never move, so Python rejects it for every slice:
s = "Python"
try:
s[::0]
except ValueError as e:
print(e)The output is slice step cannot be zero. This is a ValueError, not an IndexError. Its main effect in practice is on code that computes the step. A computed value that can reach 0 needs a guard.
Alternatives to `s[::-1]`
Slicing is not the only way to reverse a string. The built-in reversed() returns an iterator over the characters, and you can join it back into a string:
s = "Python"
print(s[::-1])
print("".join(reversed(s)))Both print nohtyP. The slice is shorter and is the common idiom. The reversed() form states its purpose more plainly to a reader who does not know slicing. It is also the better choice when you only need to loop over the characters backward and do not need a new string, because for ch in reversed(s): does not build one.
To reverse the order of words, split first, reverse the list with the same slice, and join:
text = "to be or not"
print(" ".join(text.split()[::-1]))The output is not or be to. Lists support the same slice syntax, with the same rules for defaults and negative steps.
Reversal works on code points
Reversing by slicing reverses code points, not the characters a reader sees. Some visible characters are made of a base letter followed by a combining mark. After reversal, the mark comes before its base letter and attaches to the wrong neighbor, or to nothing.
s = "cafe\u0301"
r = s[::-1]
print(len(s))
print(ascii(r))The output is:
5
'\u0301efac'The original string displays as café but has 5 code points: c, a, f, e and U+0301. In the reversed string the accent comes first, so it combines with whatever precedes it when the text is displayed. If you reverse text that may contain combining marks, emoji sequences or other multi-code-point characters, slicing is not enough. A library that segments text into grapheme clusters is needed. For plain ASCII text, s[::-1] is safe.
Summary of rules
- A negative step walks backward, so
startmust be greater thanstopto get any result. - With a negative step, an omitted
startmeans the last character and an omittedstopmeans "before the first character". stopis always excluded, in both directions.- A negative
stopcounts from the end, sos[5:-1:-1]is empty. Omitstopto reach the beginning. - A wrong direction gives
''. A step of zero raisesValueError. - Slicing reverses code points, not visible characters.
Exercise
Given s = "abcdefghij", what do s[8:2:-3], s[:6:-1] and s[2:8:-1] return?
Show answer
s[8:2:-3] visits indexes 8 and 5 (the next, 2, is the excluded stop), so it returns 'if'. s[:6:-1] starts at the default last index 9 and stops before index 6, so it visits 9, 8 and 7 and returns 'jih'. s[2:8:-1] starts at 2 and would need to move backward to reach 8, so it returns '' (an empty string).
Exercise
A learner writes word[len(word)-1:-1:-1] to reverse a string and gets an empty string. Explain why, and give two corrected versions.
Show answer
The start is the last index, len(word)-1. The stop -1 is a negative index, so Python converts it to len(word)-1 as well. Start and stop are then the same position, and nothing lies between them. Two fixes are word[::-1] and word[len(word)-1::-1]. Using "".join(reversed(word)) also works.