Sub topic 9
Trimming whitespace, characters, prefixes, and suffixes
This chapter assumes you know that Python strings are immutable and that string methods return new strings. It also assumes you can use startswith and endswith, and read a list comprehension. Trimming is the most common cleanup step for text that comes from files, user input, or network responses. It is also where a widely misunderstood argument causes quiet bugs.
The family of trimming methods
Python has five methods that remove text from the edges of a string:
| Method | What it removes | Where |
|---|---|---|
| `strip(chars=None)` | Any characters in the set `chars` (whitespace by default) | Both ends |
| `lstrip(chars=None)` | Any characters in the set `chars` (whitespace by default) | Left end only |
| `rstrip(chars=None)` | Any characters in the set `chars` (whitespace by default) | Right end only |
| `removeprefix(prefix)` | One exact piece of text, if present | Start |
| `removesuffix(suffix)` | One exact piece of text, if present | End |
None of them change the original string. Each returns a new string, so you must assign or use the result.
s = " hi "
s.strip() # result is thrown away
print(repr(s)) # ' hi ' (unchanged)
s = s.strip() # keep the result
print(repr(s)) # 'hi'Default behavior: trimming whitespace
Called with no argument, strip removes whitespace from both ends. Whitespace includes spaces, tabs, newlines, carriage returns, and other Unicode characters that str.isspace() accepts.
print(repr(" hi\n".strip())) # 'hi'
print(repr(" hi ".lstrip())) # 'hi '
print(repr(" hi ".rstrip())) # ' hi'
print(repr("\t\n hi \r\n".strip())) # 'hi'Trimming only touches the edges. Whitespace inside the string stays as it is.
print(repr(" a b ".strip())) # 'a b'If you also need to collapse the inner whitespace, use " ".join(text.split()), which a later chapter covers.
What counts as whitespace
The default whitespace set follows Unicode. A non-breaking space (\u00a0), which often appears in text copied from web pages, is stripped. A zero-width space (\u200b) is not whitespace, so strip() leaves it alone.
print(repr("\u00a0hi\u00a0".strip())) # 'hi'
print(repr("\u200bhi".strip())) # '\u200bhi'
print("\u200b".isspace()) # FalseIf invisible characters survive your cleanup, check them with repr() and ord(). Then remove them with replace or translate.
Trimming specific characters
Pass a string to strip, lstrip, or rstrip to choose which characters to remove. Removal continues from each edge until a character that is not in the set appears.
print("xxhixx".strip("x")) # hi
print("--==title==--".strip("-=")) # title
print("$1,234.50".lstrip("$")) # 1,234.50
print("line\r\n".rstrip("\r\n")) # lineA line ending can be \n, \r\n, or a lone \r. rstrip("\r\n") handles all three because the argument is a set of characters, not a sequence.
The argument is a set, not a substring
This is the main gotcha. strip("abc") does not remove the text "abc". It removes any mix of a, b, and c characters, in any order, from the edges.
print("happy.py".rstrip(".py")) # ha
print("cabbage".strip("abc")) # g
print("www.example.com".strip("w.com")) # exampleIn the first line, rstrip(".py") strips y, p, ., y, p, p, and then stops at a. The result is ha instead of happy. The bug often goes unnoticed because many test inputs happen to work. For example, "test_file.py".rstrip(".py") gives test_file, because the character before the extension is not in the set.
Two further edge cases follow from the set behavior:
strip("")removes nothing, because the set is empty.strip(None)andstrip()mean "whitespace".- Stripping can empty the string.
"000".lstrip("0")returns'', not'0'. Handle this if you strip leading zeros from numbers.
print(repr("007".lstrip("0"))) # '7'
print(repr("000".lstrip("0"))) # ''
print(repr(" x".strip(""))) # ' x'Removing an exact prefix or suffix
When you want to remove one specific piece of text, use removeprefix and removesuffix. They were added in Python 3.9. They remove the text only if the string actually starts or ends with it. Otherwise they return the string unchanged.
print("test_file.py".removesuffix(".py")) # test_file
print("v1.2".removeprefix("v")) # 1.2
print("happy.py".removesuffix(".py")) # happy
print("data.csv".removesuffix(".py")) # data.csv (unchanged)They remove at most one occurrence. This differs from strip, which repeats.
print("vvv1".removeprefix("v")) # vv1
print("vvv1".lstrip("v")) # 1
print("a.py.py".removesuffix(".py")) # a.pyOn Python versions before 3.9, guard a slice with startswith or endswith. Do not use strip as a substitute.
def remove_suffix(text, suffix):
if suffix and text.endswith(suffix):
return text[:-len(suffix)]
return text
print(remove_suffix("happy.py", ".py")) # happyThe suffix and check matters. With an empty suffix, text[:-0] is text[:0], which would return an empty string.
Choosing the right method
Worked example: cleaning lines from a file
Lines read from a file usually end in a newline, and files often contain blank lines or stray padding. A comprehension with strip handles both problems.
lines = [" alpha \n", "beta\t\n", "\n", " gamma"]
cleaned = [line.strip() for line in lines if line.strip()]
print(cleaned) # ['alpha', 'beta', 'gamma']This calls strip twice per line. For large inputs, a loop that strips once and then tests the result avoids the repeated work.
lines = [" alpha \n", "beta\t\n", "\n", " gamma"]
cleaned = []
for line in lines:
line = line.strip()
if line:
cleaned.append(line)
print(cleaned) # ['alpha', 'beta', 'gamma']An empty string is false in an if test, so if line: skips blank lines.
You can combine trimming methods when the edges hold several kinds of noise. Strip whitespace first so the prefix is at the very start, remove the prefix, then strip again.
subject = " Re: Hello "
print(repr(subject.strip().removeprefix("Re:").strip())) # 'Hello'Here is a small function that normalizes a file name with these methods. It assumes Python 3.9 or later.
def base_name(filename):
"""Return a file name without padding, quotes, or a .csv suffix."""
name = filename.strip().strip("\"'")
return name.removesuffix(".csv")
print(base_name(' "sales.csv"\n')) # sales
print(base_name("notes.txt ")) # notes.txtThe first strip() removes the whitespace. The second strip("\"'") removes any run of quote characters at either end. removesuffix then removes the extension only if it is .csv.
Common errors
- Forgetting to assign the result.
text.strip()on its own line does nothing useful. - Treating
strip("abc")as a substring removal. It removes characters from a set. Useremoveprefixorremovesuffixfor exact text. - Using
rstrip(".py")orrstrip(".txt")to remove file extensions. Names such ashappy.pyortext.txtlose extra letters. Useremovesuffix, oros.path.splitextorpathlib.Path.stemfor real file names. - Expecting
stripto clean the inside of a string. It only touches the two ends. - Assuming all invisible characters are whitespace. Zero-width characters are not stripped by default.
- Stripping digits or zeros without thinking about all-zero input.
"000".lstrip("0")returns an empty string.
Exercises
Exercise
What does "banana".strip("ba") return, and why?
Show answer
It returns 'nan'. The argument "ba" is a set of characters, so strip removes any 'b' or 'a' from both edges. On the left it removes 'b' and 'a' and stops at 'n'. On the right it removes the final 'a' and stops at 'n'. The result is 'nan'.
Exercise
You need to turn "backup.tar.gz" into "backup.tar" and leave "backup.tar" unchanged. Which method should you use, and what is wrong with "backup.tar.gz".rstrip(".gz")?
Show answer
Use "backup.tar.gz".removesuffix(".gz"). It removes the exact suffix once and returns names without that suffix unchanged. rstrip(".gz") treats ".gz" as a set of characters ('.', 'g', 'z') and would also strip any of those characters that precede the suffix. For "backup.tar.gz" it happens to give "backup.tar", but "zig.gz".rstrip(".gz") returns "zi" because the trailing g in "zig" is in the set and gets stripped too.
Exercise
Write an expression that turns the string "\n\n ## Title \n" into "Title" using strip and removeprefix.
Show answer
text.strip().removeprefix("##").strip(). The first strip removes the newlines and spaces so "##" sits at the start. removeprefix removes "##", which leaves " Title". The final strip removes the leading space and gives "Title".