Explain Codes LogoExplain Codes Logo

How do I remove a substring from the end of a string?

python
functions
regex
best-practices
Alex KataevbyAlex Kataev·Jan 16, 2025
TLDR

If you need the quick and dirty, here is what you need for substring removal:

To trim an exact end substring:

# Isn't Python awesome, it's like cutting a piece of cake! string = string[:-len(substring)] if string.endswith(substring) else string

For removing trailing characters:

# Peel those pesky characters like a bunch of overripe bananas! string = string.rstrip(chars)

Python 3.9+ users, you got it easy with the removesuffix() cool kid on the block:

# Who knew three words could bring such joy? string = string.removesuffix(substring)

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:

import re # It's like duct tape for programming string = re.sub(rf"{substring}$", "", string)

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:

def remove_specific_suffix(string, suffix): # Because you're worth it if string.endswith(suffix): return string[:-len(suffix)] return string

Snip the tail, keep the head

To remove only the last segment after a dot, use:

url = url[:url.rfind('.')] # It's not you, it's the dot at the end of you

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() and removesuffix() 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!