Skip to content

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

To remove a substring from the end of a string, the most direct approach in Python 3.9+ is the removesuffix() method. Alternatively, you can use rsplit() or replace(), though each has specific behaviors to consider.

Using removesuffix() method (Python 3.9+)

python
string = 'Hello, world!'
substring = 'world!'

result = string.removesuffix(substring)
print(result)  # Output: 'Hello, '

Using rsplit() method The rsplit() method splits a string from the right side. When you specify the substring as the delimiter and set maxsplit=1, it removes the delimiter and returns a list. The part before the delimiter becomes the first element, and the part after becomes the second (an empty string if the delimiter is at the end). You can then join the list back into a string, omitting the last element.

python
string = 'Hello, world!'
substring = 'world!'

# Split the string using the substring as the delimiter
parts = string.rsplit(substring, 1)

# Join the parts back together, omitting the substring
result = ''.join(parts)
print(result)  # Output: 'Hello, '

Using replace() method The replace() method takes two arguments: the substring to be replaced, and the replacement string. You can use an empty string as the replacement to remove the substring. Note that replace() removes all occurrences of the substring in the string, not just the one at the end, which may not be suitable if the substring appears elsewhere.

python
string = 'Hello, world!'
substring = 'world!'

# Replace the substring with an empty string
result = string.replace(substring, '')
print(result)  # Output: 'Hello, '

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.