bytes.removesuffix()
The mirror of removeprefix, and the correct tool for file extensions. Matches the exact sequence, once, and is a no-op when absent.
Demo
When the data ends with the exact suffix it is removed; otherwise the data is returned unchanged. The third case is the one that justifies the method: text.txt becomes text, where rstrip(b".txt") would have chewed through to te because it strips a set of bytes. The doubled case shows the "once" rule — namexx with suffix x loses one x.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| suffix | bytes | yes | The exact byte sequence to remove from the end. An empty suffix is a harmless no-op. |
Return value
bytes — The data with suffix removed from the end if it is there — otherwise the data unchanged. Never raises for a missing suffix.
Common patterns
stem = filename.removesuffix(b'.txt')
body = frame.removesuffix(b'\r\n')
stem = d[:-len(s)] if s and d.endswith(s) else d
Examples
Pitfalls
b'namexx'.removesuffix(b'x')
while d.endswith(b'x'): d = d.removesuffix(b'x')
b'file.txt'.removesuffix(b'.text')
if not name.endswith(b'.txt'): raise ValueError('not a txt')
s = b'' b'abc'[:-len(s)]
b'abc'.removesuffix(b'')
When to use
- Stripping a file extension or other exact trailer
- Anywhere rstrip was being misused for an exact suffix
- Optional suffixes where absence is normal
- Removing a SET of trailing bytes → rstrip
- A suffix that must be present → check with endswith and raise
- Supporting Python 3.8 or older without a fallback
Notes
FAQ
Because rstrip strips a SET of bytes — dot, t, x — from the right, repeatedly, until a byte outside the set appears. On b"text.txt" it removes .txt and then keeps eating the t and x of "text". removesuffix matches the exact sequence once.
b'text.txt'.rstrip(b'.txt') # b'te' b'text.txt'.removesuffix(b'.txt') # b'text'