0
0
PythonHow-ToBeginner · 3 min read

How to Remove Suffix from String in Python Easily

In Python 3.9 and later, you can remove a suffix from a string using the str.removesuffix(suffix) method. This method returns a new string with the specified suffix removed if it exists; otherwise, it returns the original string unchanged.
📐

Syntax

The syntax to remove a suffix from a string is:

string.removesuffix(suffix)

Here:

  • string is your original text.
  • suffix is the ending part you want to remove.
  • The method returns a new string without the suffix if it matches exactly at the end.
python
result = "filename.txt".removesuffix(".txt")
print(result)
Output
filename
💻

Example

This example shows how to remove the suffix ".txt" from a filename string. If the suffix is present, it is removed; if not, the original string stays the same.

python
filename1 = "document.txt"
filename2 = "image.png"

print(filename1.removesuffix(".txt"))  # Removes suffix
print(filename2.removesuffix(".txt"))  # No suffix to remove, returns original
Output
document image.png
⚠️

Common Pitfalls

One common mistake is trying to remove a suffix that is not exactly at the end of the string, which will leave the string unchanged. Another is using older Python versions (before 3.9) where removesuffix does not exist.

Before Python 3.9, you can remove a suffix by checking and slicing manually.

python
text = "example.txt"

# Wrong way (does not remove suffix if not at end)
print(text.removesuffix(".tx"))  # Output: example.txt

# Older Python version way:
if text.endswith(".txt"):
    text = text[:-4]
print(text)  # Output: example
Output
example.txt example
📊

Quick Reference

MethodDescriptionPython Version
str.removesuffix(suffix)Removes suffix if present at end3.9+
Manual slicing with endswith()Check suffix and slice stringAll versions

Key Takeaways

Use str.removesuffix(suffix) in Python 3.9+ to remove a suffix easily.
If the suffix is not at the end, the original string remains unchanged.
For older Python versions, use endswith() and slicing to remove suffixes.
Always check the Python version before using removesuffix to avoid errors.