How do I remove a substring from the end of a string?
If you need the quick and dirty, here is what you need for substring
removal:
To trim an exact end substring:
For removing trailing characters:
Python 3.9+ users, you got it easy with the removesuffix()
cool kid on the block:
And if pinpoint precision is what you seek, strap in for a wild ride into custom functions and regex!
Implementing surgical substring removal
Sometimes, you need a scalpel instead of a chainsaw. Here's some nifty tools when the built-ins just don't cut it.
Regex: the dark wizard of Python
Flex your pattern-finding muscles with Python's re
module:
The $
ensures the last-minute breakup happens only at the end of the string.
Custom function: because no one else gets me
If your tastes are a bit more specific, craft your own function:
Snip the tail, keep the head
To remove only the last segment after a dot, use:
Unravelling the mysteries of strip, removeprefix and removesuffix
In the world of Python strings, strip
, removeprefix
, and removesuffix
are three musketeers with distinct personalities:
strip()
is the free spirit, removing characters found in a set from both ends.removeprefix()
andremovesuffix()
are the responsible kin, surgically removing only the exact beginning or end substring.
Always invite the right musketeer for the task!
Expect the unexpected: corner cases
Strings can hide surprises! Be wary of:
- Sneaky substrings appearing multiple times.
- Empty strings or substrings as long as the string.
- The immutable nature of strings in Python!
From the annals of Python history: PEP-616
If you crave backstory, PEP-616 introduced removeprefix()
and removesuffix()
in Python 3.9. Be warned, it's not bedtime reading!
Was this article helpful?