Sub topic 5
Slicing with start and stop
This chapter assumes you can run Python code, assign strings to variables, use print() and len(), and read a simple try/except block. It also assumes you already know how positive and negative indexes pick one character. Here we move from one character to a range of characters.
What a slice is
A slice is an expression that returns a new string made from a run of characters in the original. You write it with square brackets and a colon:
s = "Python"
print(s[0:2])This prints Py. The form is s[start:stop]. Python begins at index start and stops before index stop. The character at stop is not included.
The stop index is excluded
The half-open range is the most common source of confusion. Think of the indexes as sitting between characters:
P y t h o n
0 1 2 3 4 5 6The slice s[0:2] takes everything between position 0 and position 2, which is P and y.
Half-open ranges have two useful properties:
- The length of
s[start:stop]isstop - startwhen both bounds are in range. Sos[2:5]has 3 characters. - Two neighbouring slices fit together with no gap and no overlap.
s[:3] + s[3:]always equalss.
Negative bounds
Slice bounds accept negative numbers with the same meaning as in indexing. A negative number counts from the end, so -1 refers to the position of the last character.
s = "Python"
print(s[1:4])
print(s[-4:-1])
print(s[1:-1])The output is yth, tho and ytho. The last line shows a handy pattern: s[1:-1] drops the first and last characters.
Leaving out start or stop
You can omit either bound. A missing start means the beginning of the string. A missing stop means the end of the string.
s = "Python"
print(s[0:2])
print(s[2:])
print(s[:3])
print(s[-3:])
print(s[:])This prints Py, thon, Pyt, hon and Python. Note that s[-3:] is the way to take the last three characters. The expression s[:] copies the whole string, although for strings the result may be the very same object, because strings cannot be changed.
Slices that go past the ends
An out-of-range index raises IndexError. A slice does not. Python clamps the bounds to the valid range instead.
s = "Python"
print(s[2:100])
print(repr(s[10:]))
print(repr(s[3:1]))The output is:
thon
''
''s[2:100]clamps100down to6, so you getthon.s[10:]starts past the end, so nothing is selected and the result is an empty string.s[3:1]has a start after its stop. With the default positive step, nothing can be selected, so the result is again an empty string.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Expecting `s[0:2]` to include index 2 | You get 2 characters, not 3 | Remember that `stop` is excluded |
| Using `s[-3:-1]` to get the last three characters | You lose the final character | Use `s[-3:]` |
| Expecting an error from `s[10:]` | You get `''` with no error | Check `len()` when you need to validate input |
| Writing `s[3:1]` to go backwards | You get `''` | Use a negative step, covered in a later chapter |
Putting it together
A small helper shows how slicing works with computed bounds:
def first_and_last(text, n):
return text[:n], text[-n:]
print(first_and_last("Python", 2))
print(first_and_last("hi", 5))The first call prints ('Py', 'on'). The second prints ('hi', 'hi'), because both slices clamp to the full string. There is no error. One further caveat: with n = 0, text[-0:] is text[0:], which is the whole string, not an empty one.
Exercise
Given s = "abcdefghij", what do s[2:5], s[:-7] and s[8:20] each return?
Show answer
s[2:5] returns 'cde' (indexes 2, 3 and 4). s[:-7] returns 'abc', because -7 is index 3 and the stop is excluded. s[8:20] returns 'ij', because the stop of 20 is clamped to the length of 10.
Exercise
Write a slice expression that removes the first two and last two characters of a string s. What does it return for s = "abc"?
Show answer
Use s[2:-2]. For "abc" it is s[2:1], which has a start after its stop, so it returns an empty string ''.