str.removesuffix()
Removes an exact piece of text from the end of a string, if the string ends with it. Otherwise the string comes back as it is.
str.removesuffix(suffix)removesuffix() checks whether the string ends with suffix and, if it does, returns everything before it. If it does not, you get the original text back. It was added in Python 3.9.
Its classic job is removing a known file extension, such as ".csv", or a fixed ending like " kg" before you turn text into a number.
Do not use str.rstrip() for this: rstrip(".csv") removes any of the characters ., c, s and v from the end, so "basics.csv" turns into "basi". removesuffix() removes the exact text, once.
Parameters
| Parameter | What it is |
|---|---|
suffixrequired | The exact text to remove from the end. |
Return value
A new string without the suffix, or a copy of the original if it did not end with it.
Examples
1Remove a file extension
print("report.csv".removesuffix(".csv"))
print("report.pdf".removesuffix(".csv"))report report.pdf
2removesuffix() vs rstrip()
name = "basics.csv"
print(name.rstrip(".csv"))
print(name.removesuffix(".csv"))basi basics
3Turn weights written as text into numbers
weights = ["2.5 kg", "0.8 kg", "12 kg"]
total = sum(float(w.removesuffix(" kg")) for w in weights)
print(total, "kg")15.3 kg
4Rename many files on paper
files = ["jan.txt", "feb.txt", "mar.txt"]
for f in files:
print(f, "->", f.removesuffix(".txt") + ".md")jan.txt -> jan.md feb.txt -> feb.md mar.txt -> mar.md
Common mistakes
Case differences
The ending must match exactly, including case. Lower-case a copy to check, but cut the original.
name = "PHOTO.JPG"
print(name.removesuffix(".jpg"))
if name.lower().endswith(".jpg"):
print(name[:-4])PHOTO.JPG PHOTO
Questions people ask
What is the difference between removesuffix() and rstrip()?
removesuffix(".txt") removes exactly ".txt" once. rstrip(".txt") removes any mix of ., t and x characters from the end.
How do I remove any extension, not a known one?
Use name.rsplit(".", 1)[0] or pathlib.Path(name).stem.
What can I use before Python 3.9?
if s.endswith(suf): s = s[:-len(suf)] (only when suf is not empty).