Sub topic 6
Leaving out start or stop
This chapter assumes you can run Python code, assign a string to a variable, use print() and len(), and read a simple try/except block. It also assumes you know the s[start:stop] form, where start is included and stop is excluded. Here you will see what Python does when you leave one bound out, or both.
What an omitted bound means
In s[start:stop], either bound can be left empty. Python then fills in a default based on the direction of the slice. With the default step of 1, which moves left to right:
- A missing
startmeans "from the beginning" (index 0). - A missing
stopmeans "through the end" (indexlen(s)).
s = "Python"
print(s[0:2])
print(s[2:])
print(s[:3])
print(s[-3:])
print(s[:])This prints:
Py
thon
Pyt
hon
PythonThe five lines show these cases:
| Expression | Meaning | Result |
|---|---|---|
| `s[0:2]` | Both bounds given | `Py` |
| `s[2:]` | From index 2 to the end | `thon` |
| `s[:3]` | From the beginning up to, not including, index 3 | `Pyt` |
| `s[-3:]` | The last three characters | `hon` |
| `s[:]` | Everything | `Python` |
Negative numbers work in either position. s[-3:] starts three characters from the end and runs to the end, so it is the usual way to take "the last n characters".
Splitting at a position
An omitted bound lets you name the split point once. The two halves of a split always rejoin into the original string:
s = "Python"
n = 2
head = s[:n]
tail = s[n:]
print(head)
print(tail)
print(head + tail == s)Because stop is excluded and start is included, s[:n] and s[n:] never overlap and never skip a character. This works for any n. Writing s[0:n] and s[n:len(s)] says the same thing with more noise.
The full slice
s[:] leaves out both bounds, so it selects the whole string. For a list, items[:] makes a shallow copy, and you may see it used that way. For a string the copy has no practical effect. Strings cannot change, so CPython can return the same object:
s = "Python"
t = s[:]
print(t == s)
print(t is s)Both lines print True in CPython. Treat is here as an implementation detail and don't rely on it. The takeaway is that s[:] is safe but rarely useful on strings. It matters more when you write code that must work for both strings and lists.
Common mistake: `-0`
Negative indexes count from the end, but -0 is just 0. Code that computes a bound such as -n therefore behaves badly when n is zero:
s = "Python"
n = 0
print(repr(s[-n:]))
print(repr(s[:-n]))This prints:
'Python'
''You might expect s[-n:] to mean "the last 0 characters" and return an empty string. Instead it becomes s[0:], which returns the whole string. Likewise s[:-n] becomes s[:0], which is empty, not "everything except the last 0 characters".
Choosing between forms
Prefer the shortest form that states your intent:
- Use
s[:n]for "the first n characters", nots[0:n]. - Use
s[n:]for "everything after the first n characters". - Use
s[-n:]for "the last n characters", providednis at least 1. - Use
s[:-n]for "everything except the last n characters", with the same condition.
Exercise
Given s = "documentation", write one expression that returns everything except the first 3 and the last 4 characters, and one that returns only the last 4 characters. What do they return?
Show answer
s[3:-4] returns 'ument' and s[-4:] returns 'tion'. The first has both bounds given. The second leaves out stop, so the slice runs to the end.
Exercise
What does "Python"[:-0] return, and why?
Show answer
It returns '', an empty string. -0 equals 0, so the expression is "Python"[:0], which stops before index 0 and selects nothing.