Sub topic 6
Leaving Out Start or Stop
This chapter assumes you can read s[i] and s[a:b] with positive and negative numbers, and that you know len() and basic try/except. Here you will learn what Python does when you leave out a bound, and which omissions are safe or risky.
What an omitted bound means
In s[start:stop], either number can be left blank. Python then substitutes a default so the slice reaches the edge of the string:
- A missing
startmeans "begin at the beginning". - A missing
stopmeans "run to the end".
s = "Python"
print(s[:2])
print(s[2:])
print(s[-3:])
print(s[:-3])
print(s[:])This prints Py, thon, hon, Pyt and Python.
Each result matches an explicit form. s[:2] is s[0:2], and s[2:] is s[2:len(s)]. s[-3:] starts three characters from the end and runs to the end. s[:-3] starts at the beginning and stops before the last three characters.
The two forms below are complements, and the second one is the useful idea:
s[:n]is the firstncharacters.s[n:]is everything after them.
Because stop is excluded and start is included, the same n can serve as both bounds without overlap or gap:
s = "Python"
for n in range(0, len(s) + 1):
assert s[:n] + s[n:] == s
print("split at any n reassembles the string")This property is why half-open slices (start included, stop excluded) are the Python convention. You never need n - 1 or n + 1 to avoid double-counting the boundary character.
Summary of the forms
| Expression | Equivalent explicit form | Meaning |
|---|---|---|
| `s[:n]` | `s[0:n]` | first `n` characters |
| `s[n:]` | `s[n:len(s)]` | everything from index `n` |
| `s[-n:]` | `s[len(s)-n:]` | last `n` characters (for `n > 0`) |
| `s[:-n]` | `s[0:len(s)-n]` | everything except the last `n` (for `n > 0`) |
| `s[:]` | `s[0:len(s)]` | the whole string |
How the defaults are chosen
An omitted bound is stored as None. When Python evaluates the slice, it replaces None with a concrete number. That number depends on the sign of the step, which is the optional third value you will use in a later chapter. With no step, the step is 1.
You can see the substitution directly with a slice object, which a later chapter covers in detail:
s = "Python"
print(slice(None, 3).indices(len(s)))
print(slice(2, None).indices(len(s)))
print(slice(None, None).indices(len(s)))
print(slice(None, None, -1).indices(len(s)))This prints (0, 3, 1), (2, 6, 1), (0, 6, 1) and (5, -1, -1). In the last tuple, -1 as a stop is a concrete marker meaning "stop before index 0". It is not the negative index for the last character.
Writing the explicit 0 is not always the same as omitting the start. With a negative step the two behave very differently:
s = "Python"
print(s[::-1])
print(s[0::-1])The first line prints nohtyP. The second prints P. An explicit 0 is a real start position, so walking backward from index 0 yields only one character. An omitted start becomes the last index. Keep this in mind when you reach reversing in a later chapter.
Full copies with `s[:]`
s[:] selects every character, so its value always equals s. With lists, [:] creates a new list, which is why you may have seen it called a "shallow copy idiom". With strings the idiom has no practical use, because strings cannot be changed:
s = "Python"
t = s[:]
print(t == s)
print(t is s)The first line prints True. The second prints True in CPython, the standard implementation, because slicing an exact str over its whole length returns the same object. Treat that identity result as an implementation detail. Code should never depend on is for strings. If you see s[:] applied to a string in code you inherit, it is usually a habit carried over from lists and can be removed.
Safe and unsafe omissions
Omitted bounds are safe at the ends of the string, because Python clamps the result and never raises an error for a slice. That means these never fail, even on an empty string:
print(repr(""[:3]))
print(repr(""[2:]))
print(repr("ab"[:100]))They print '', '' and 'ab'. Compare this with ""[0], which raises IndexError. Slices are the right tool when the string might be shorter than you expect.
The `-0` trap
Slicing the last n characters with s[-n:] breaks when n is zero. The value -0 is just 0, so the slice starts at the beginning:
s = "Python"
n = 0
print(repr(s[-n:]))
print(repr(s[:-n]))The first line prints 'Python', not an empty string. The second prints '', not the whole string. Both are the opposite of what the "last n" and "all but last n" readings suggest. If n comes from a variable, guard against zero:
def last_n(text, n):
if n <= 0:
return ""
return text[-n:]
def all_but_last(text, n):
if n <= 0:
return text
return text[:-n]
print(repr(last_n("Python", 3)))
print(repr(last_n("Python", 0)))
print(repr(last_n("Python", 10)))
print(repr(all_but_last("Python", 0)))
print(repr(all_but_last("Python", 2)))The output is 'hon', '', 'Python', 'Python' and 'Pyth'. A value of n larger than the length is fine, because the slice is clamped to the whole string.
The `-1` from a failed search
A similar trap appears when the stop or start comes from a search method. str.rfind() returns -1 when nothing is found, and -1 is a valid negative index:
for name in ["report.final.txt", "README"]:
dot = name.rfind(".")
print(name[:dot], "|", name[dot + 1:])For report.final.txt the output is report.final | txt, which is correct. For README, dot is -1, so name[:-1] is READM and name[0:] is README. The output line is READM | README. Nothing raised an error, but the answer is wrong. Check for -1 before slicing:
def split_extension(name):
dot = name.rfind(".")
if dot == -1:
return name, ""
return name[:dot], name[dot + 1:]
print(split_extension("report.final.txt"))
print(split_extension("README"))This prints ('report.final', 'txt') and ('README', '').
Patterns that rely on omitted bounds
Removing a known prefix
When you know a prefix is present, slice from its length:
line = "ERROR: disk full"
prefix = "ERROR: "
if line.startswith(prefix):
message = line[len(prefix):]
print(message)This prints disk full. Using len(prefix) instead of a hard-coded 7 keeps the code correct if the prefix changes. Since Python 3.9 there is also str.removeprefix(), which does the check and the slice in one call. The slice form is still worth knowing because it works on other sequences and on versions before 3.9.
Taking a fixed-size head and tail
code = "ABC-12345"
print(code[:3])
print(code[4:])
print(code[-2:])This prints ABC, 12345 and 45. Each expression names only the bound that matters, and the other end is implied.
Consuming a string in chunks
Because text[:size] and text[size:] partition the string with no overlap, they work well in a loop:
def chunks(text, size):
parts = []
while text:
parts.append(text[:size])
text = text[size:]
return parts
print(chunks("abcdefgh", 3))This prints ['abc', 'def', 'gh']. The last chunk is shorter, and no special case is needed. text[:3] on a two-character string simply returns both characters, and text[3:] then returns the empty string, which ends the loop.
The loop creates a new string on every pass, so for very long inputs a range(0, len(text), size) loop that slices text[i:i + size] does less copying. For short strings the version above is easier to read.
Common mistakes
- Using
s[:n-1]to getncharacters.s[:n]already givesn, because the stop is excluded. - Reading
s[:-1]as "up to and including the last character". It drops the last character. - Replacing an omitted start with
0when the step is negative. This changes the result, ass[::-1]versuss[0::-1]showed. - Passing a variable that may be
0or-1as-nor as a stop without guarding it. - Writing
s[:]on a string expecting a copy that is independent of the original. Strings are immutable, so there is nothing to protect against.
Exercise
Given s = "abcdef" and n = 2, what do s[:n], s[n:], s[-n:] and s[:-n] return? Then say what the last two return if n = 0.
Show answer
With n = 2: s[:n] is 'ab', s[n:] is 'cdef', s[-n:] is 'ef' and s[:-n] is 'abcd'. With n = 0, -n equals 0, so s[-n:] is s[0:], which is the whole string 'abcdef', and s[:-n] is s[:0], which is the empty string ''.
Exercise
Write a function without_suffix(text, suffix) that returns text with suffix removed from the end if it is present, and returns text unchanged otherwise. It must work correctly when suffix is the empty string, and it must not use str.removesuffix().
Show answer
def withoutsuffix(text, suffix):
if suffix and text.endswith(suffix):
return text[:-len(suffix)]
return text
The check suffix and ... handles the empty suffix. Without it, len(suffix) is 0, so text[:-0] would be text[:0], which returns an empty string instead of the original text. For example, `withoutsuffix("report.txt", ".txt") returns 'report', and without_suffix("report", "") returns 'report'`.