How to remove a string suffix in Python?

How do I remove part of a string in Python from the end (remove a suffix of the string)?

Using str.removesuffix() (Python 3.9+): The removesuffix() method is a straightforward way to remove a specified suffix from the end of a string if it exists. If the string does not end with the specified suffix, the original string is returned. It’s clean and super-readable—perfect for newer Python versions.

text = "hello_world"
result = text.removesuffix("_world")
print(result)  # Output: hello

This method is the best choice if you’re working with Python 3.9 or later and just want to remove part of string Python.

Using string slicing: I often find this approach handy, especially when I’m dealing with earlier Python versions where removesuffix() isn’t available. You just need to know the length of the suffix to slice it off.

text = "hello_world"
suffix = "_world"
if text.endswith(suffix):
    result = text[:-len(suffix)]
print(result)  # Output: hello

It’s simple and doesn’t rely on any special methods—just slicing. Definitely worth keeping in mind if you’re working in a mixed environment but still need to remove part of string Python.

Using str.replace() with a condition: While not as elegant as the other methods, replace() can work in scenarios where you can’t rely on slicing or removesuffix(). However, it requires careful use to avoid replacing unintended parts of the string.

text = "hello_world"
if text.endswith("_world"):
    result = text.replace("_world", "", 1)
print(result)  # Output: hello

Keep in mind, though, that replace() modifies all occurrences by default, so using the 1 count parameter and checking with endswith() ensures precision. This is another handy trick to remove part of string Python, but only use it if you’re aware of the limitations.