str.removesuffix()
Strip an exact suffix — the intent-preserving alternative to rstrip that does not surprise you with character-set semantics.
Demo
removesuffix strips an EXACT substring from the end — at most once. If the string does not end with the suffix, the original is returned unchanged. Unlike rstrip, the argument is a substring, not a character set — ".py" removes exactly ".py" once, not any trailing ".", "p", or "y" characters in any order.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| suffix | str | yes | The exact substring to remove from the end. If the string does not end with this exact substring, the original is returned unchanged. |
Return value
str — A copy of the string with the exact SUBSTRING `suffix` removed from the end, IF the string ends with it. Otherwise the string is returned unchanged. Removes at most one occurrence.
Common patterns
stem = filename.removesuffix(".py")
name = package.removesuffix("-1.0.0")
inner = s.removeprefix("(").removesuffix(")")
Examples
Pitfalls
"test.py.py".removesuffix(".py")
s = "test.py.py" while s.endswith(".py"): s = s.removesuffix(".py")
"hello".removesuffix("")
if suffix: s = s.removesuffix(suffix)
"happy.py".rstrip(".py")
"happy.py".removesuffix(".py")
"basename.py".removesuffix(".py") # 3.8
def removesuffix(s, x): return s[:-len(x)] if x and s.endswith(x) else s
When to use
- Stripping a KNOWN, exact trailing substring
- File extension removal
- Version or namespace suffix trimming
- Any place rstrip would have been the wrong tool because of character-set semantics
- Multi-occurrence removal → loop with while + endswith
- Character-set removal → str.rstrip is the correct tool
- Case-insensitive suffix removal → casefold both sides, or use regex
- Python 3.8 or earlier → use the s[:-len(x)] idiom instead
Notes
FAQ
Because rstrip strips a CHARACTER SET, not a substring. "happy.py".rstrip(".py") strips trailing y, p, and dot in any combination — you end up with "ha", not "happy". removesuffix does exact-suffix removal, which is almost always what people meant when they reached for rstrip.