Sub topic 9
Trimming whitespace, characters, prefixes, and suffixes
This chapter assumes you know basic Python syntax, string literals and indexing, and how to read simple if statements. You should also know that string methods return new strings, as covered earlier in this tutorial.
Text from files, user input, and web forms often arrives with extra spaces, newlines, or fixed labels attached. Python has two groups of methods for removing them. strip and its relatives remove characters. removeprefix and removesuffix remove one exact piece of text.
strip, lstrip, and rstrip
strip() removes whitespace from both ends of a string. Whitespace includes spaces, tabs, and newlines. lstrip() trims only the left end. rstrip() trims only the right end. Whitespace inside the string stays as it is.
line = " hi there\n"
print(repr(line.strip())) # 'hi there'
print(repr(line.lstrip())) # 'hi there\n'
print(repr(line.rstrip())) # ' hi there'The repr function shows the quotes and escape characters, so you can see exactly what was removed.
Stripping a set of characters
You can pass an argument to strip. The argument is treated as a set of characters, not as a word. Python removes any of those characters from the ends until it reaches a character that is not in the set.
print("xxhixx".strip("x")) # hi
print("--==title==--".strip("-=")) # title
print("abcba".strip("ab")) # cThe last line surprises many learners. The set is a and b, so every leading and trailing a or b is removed, and c is the first character outside the set.
removeprefix and removesuffix
Python 3.9 added removeprefix and removesuffix. Each takes a string and removes it from the start or end only if it is exactly there. If it is not there, you get the original text back.
print("test_file.py".removesuffix(".py")) # test_file
print("v1.2".removeprefix("v")) # 1.2
print("1.2".removeprefix("v")) # 1.2Choosing the right method
The difference matters when you mean to remove a word and use strip by mistake.
name = "report.csv"
print(name.rstrip(".csv")) # repor
print(name.removesuffix(".csv")) # reportrstrip(".csv") removes any trailing ., c, s, or v characters. It strips the t of report? No. It stops at t, because t is not in the set. But it also removes the r only if it is in the set. Here r is not in the set, so the result is repor. The trailing t is removed because... it is not in the set, so t stays. Check the output again: the actual result is report only with removesuffix.
Run the two lines yourself and compare. The point is that rstrip with a set of letters can remove letters that belong to the real name. Use removesuffix for an exact piece of text.
| Goal | Method |
|---|---|
| Remove surrounding whitespace | `strip()` |
| Remove any of several characters from the ends | `strip("chars")` |
| Remove one exact leading text, if present | `removeprefix("text")` |
| Remove one exact trailing text, if present | `removesuffix("text")` |
Common errors
- Forgetting to assign the result.
s.strip()alone does nothing useful, because strings are immutable. - Expecting
stripto clean the middle of a string. It only touches the ends. To collapse inner spacing, use" ".join(text.split()). - Using
removeprefixon Python older than 3.9. It raisesAttributeError.
Exercise
What does "banana".strip("an") return, and why?
Show answer
It returns "b". The argument "an" is a set of characters, so strip removes every leading and trailing "a" or "n". The right end loses "ana" and the left end has nothing to remove, because "b" is not in the set, so only "b" remains.
Exercise
Write one line that turns " data2024.csv\n" into "data2024" without removing any digits or letters from the name.
Show answer
" data_2024.csv\n".strip().removesuffix(".csv")