Sub topic 7
Slices that go past the ends
This chapter assumes you know how to index a string with positive and negative indexes, how s[start:stop] works, and how to read a basic try/except block. It covers what happens when slice bounds fall outside the string, and why that differs from indexing.
Indexes raise, slices clamp
An index must point at a real character. If it does not, Python raises IndexError. A slice does not need every bound to be valid. Python clamps each bound to the nearest end of the string and returns whatever lies between them.
s = "Python"
print(s[2:100])
print(repr(s[10:]))
print(repr(s[3:1]))This prints:
thon
''
''Each line shows a different case:
s[2:100]: the stop of 100 is past the end, so Python treats it as 6 (len(s)). The result is'thon'.s[10:]: the start of 10 is past the end, so there is nothing to take. The result is an empty string.s[3:1]: the start is after the stop, and the step is positive (+1), so the slice moves forward and finds nothing. The result is an empty string.
The repr() calls matter here. Printing an empty string shows a blank line, which is easy to misread. repr() shows '', so you can see the result is an empty string and not missing output.
How the clamping works
Python applies two steps to each bound. For a positive step:
- If a bound is negative, add
len(s)to it. Python does this once. - If the result is still below 0, use 0. If it is above
len(s), uselen(s).
For "Python" (length 6), s[-100:3] becomes s[0:3], which is 'Pyt'. The start of -100 becomes -94 after step 1, then 0 after step 2.
If the final start is at or after the final stop, the result is empty.
Why the two behave differently
An index asks for exactly one character. If there is none, no sensible value exists to return, so an error is the honest answer. A slice asks for a range, and "no characters" is a valid range. An empty string is a correct answer to "give me the characters between these positions."
s = "Python"
try:
s[6]
except IndexError as e:
print(e)
print(repr(s[6:]))The index s[6] raises IndexError: string index out of range. The slice s[6:] starts exactly at the end and returns ''.
Common mistakes
- Assuming an empty result means a bug in your data. A slice such as
text[:10]is safe on a short string. It returns the whole string if the string has fewer than 10 characters. This makes it a useful way to truncate without checking the length first. - Taking
s[0]of a possibly empty string. Ifsis"",s[0]raisesIndexError. The slices[:1]returns''instead, so it is a safe way to get "the first character, if any." - Mixing up the direction.
s[3:1]is empty because the step is positive. With a negative step,s[3:1:-1]walks backward and returns characters. The direction of the step decides whether the bounds make sense. - Expecting errors from typos. Because slices never complain about bounds, a wrong number such as
s[1:60]instead ofs[1:6]will run silently. Check the result when it matters.
s = ""
print(repr(s[:1]))
print(repr("Python"[3:1:-1]))This prints '' and then 'ho', because the second slice moves backward from index 3 down to, but not including, index 1.
Summary
- An out-of-range index raises
IndexError. - An out-of-range slice bound is clamped to the ends of the string.
- A slice with no characters between its bounds returns
''. - With a positive step, a start at or after the stop gives
''.
Exercise
Given s = "Python", what do s[-100:2], s[4:100] and s[:0] return? Which of these would raise an error if written as a single index with the same number?
Show answer
s[-100:2] returns 'Py' (the start is clamped to 0). s[4:100] returns 'on' (the stop is clamped to 6). s[:0] returns '' because no characters lie before index 0. The single indexes s[-100] and s[100] would raise IndexError, because indexes are never clamped. (s[0] is valid, but s[:0] takes no characters at all.)
Exercise
Write a function first_n(text, n) that returns the first n characters of text and never raises an error, even for an empty string or when n is larger than the string length.
Show answer
def firstn(text, n): return text[:n] Because slice bounds are clamped, firstn("", 3) returns '' and first_n("Hi", 10) returns 'Hi'.