Remove a suffix from a String in Python

avatar

Borislav Hadzhiev

Last updated: Aug 18, 2022

banner

Photo from Unsplash

Remove a suffix from a String in Python #

Use the str.removesuffix() method to remove the suffix from a string, e.g. without_suffix = my_str.removesuffix('@@@'). The removesuffix() method will return a new string with the specified suffix removed.

main.py
# ✅ Remove suffix from string (Python 3.9+) my_str = '$$$melon@@@' without_suffix = my_str.removesuffix('@@@') print(without_suffix) # 👉️ '$$$melon' without_prefix = my_str.removeprefix('$$$') print(without_prefix) # 👉️ 'melon@@@' # ----------------------------------------------------- # ✅ Remove suffix from string (older than Python 3.9) def removesuffix(string, suffix): if string.endswith(suffix): return string[:-len(suffix)] return string print(removesuffix('orange!!!', '!!!')) # 👉️ 'orange' print(removesuffix('pear**', '**')) # 👉️ 'pear'

The first example uses the str.removesuffix() method to remove the suffix from a string.

The method is available in Python version 3.9 or newer.

The str.removesuffix method checks if the string ends with the specified suffix and if it does, the method returns a new string excluding the suffix, otherwise it returns a copy of the original string.

main.py
print('apricot,,,'.removesuffix(',,,')) # 👉️ 'apricot' print('grapefruit=='.removesuffix('==')) # 👉️ 'grapefruit'

The method does not change the original string, it returns a new string. Strings are immutable in Python.

If you use an older version of Python, you can implement the removesuffix method yourself.

main.py
def removesuffix(string, suffix): if string.endswith(suffix): return string[:-len(suffix)] return string print(removesuffix('orange!!!', '!!!')) # 👉️ 'orange' print(removesuffix('pear**', '**')) # 👉️ 'pear'

The removesuffix function checks if the passed in string ends with the specified substring.

If the string doesn't end with the specified substring, the function returns the string as is.

If the string ends with the substring, the function returns a slice of the function up to the specified substring.

We used negative string slicing to exclude the suffix from the new string slice.

If you need to remove a suffix from a string, ignoring the case, convert the suffix and the string to lowercase.

main.py
def removesuffix(string, suffix): if string.lower().endswith(suffix.lower()): return string[:-len(suffix)] return string print(removesuffix('orangeABC', 'abc')) # 👉️ 'orange' print(removesuffix('pearZxc', 'zXC')) # 👉️ 'pear'

We used the str.lower() method to convert the string and the suffix to lowercase.

The str.lower method returns a copy of the string with all the cased characters converted to lowercase.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.