r/pythontips • u/ClickOk5811 • 12d ago
Standard_Lib Tip: lstrip("test_") doesn’t remove the prefix “test_”. Use removeprefix instead
strip, lstrip and rstrip don’t take a prefix or suffix. They take a set of characters and remove any of them from the edge. That looks right on some inputs and silently breaks on others:
>>> "docs.csv".rstrip(".csv")
'do'
>>> "settings".lstrip("test_")
'ings'In the first one, .csv is treated as the characters ., c, s, v, so the s and c at the end of docs get eaten too. In the second, s, e, t and _ are all in the set, so settings loses its first four letters.
Part of what makes this a trap is that it often works by coincidence:
>>> "test_utils.py".lstrip("test_")
'utils.py'Since Python 3.9 there are methods that do what people usually mean:
>>> "settings".removeprefix("test_")
'settings'
>>> "test_utils.py".removeprefix("test_")
'utils.py'
>>> "docs.csv".removesuffix(".csv")
'docs'They remove the exact string once, and only if it’s there. If the prefix or suffix isn’t present, you get the original string back, and repeating isn’t a problem:
>>> "report.csv.csv".removesuffix(".csv")
'report.csv'When to still use strip**:** when you really want to trim a set of characters, like whitespace or punctuation (line.strip() or text.strip(".,;")).
Compatibility: on Python versions before 3.9, removeprefix and removesuffix don’t exist. A small helper using startswith and slicing does the same job.
Do you have a favorite “looks right, works by coincidence” Python trap?
1
u/__M4V3RICK 10d ago
You could simply use split() or a combination of split() and join() or replace() methods to have more control and accuracy in results. Keep strip() to get rid of whitespaces only.