Call text.removesuffix(suffix) (introduced in Python 3.9) to strip an exact literal suffix from the end of a string—never use text.rstrip(suffix), which treats its argument as an unordered set of individual characters rather than an exact substring and accidentally deletes extra characters from the end of your string.
Basic Example
filename = "archive_2026.tar.gz"
# 1. Recommended (Python 3.9+): Exact literal suffix removal
clean_name = filename.removesuffix(".gz")
print(clean_name)
# Output: archive_2026.tar
# 2. If the suffix is not present, `.removesuffix()` returns the original string unchanged:
print(filename.removesuffix(".zip"))
# Output: archive_2026.tar.gz
# 3. ❌ Common bug: `.rstrip()` strips ANY character in the set {'.', 'g', 'z'}:
print("config.gz".rstrip(".gz"))
# Output: confi (accidentally stripped the 'g' from 'config'!)
Key Details & Edge Cases
.removesuffix()removes at most ONE occurrence of the exact suffix:"report.bak.bak".removesuffix(".bak")returns"report.bak"(unlike.rstrip(), which strips repeatedly). If you need to strip repeated occurrences of a multi-character suffix, use awhile s.endswith(suffix): s = s.removesuffix(suffix)loop orre.sub(rf"(?:{re.escape(suffix)})+$", "", s).
- Stripping any one of multiple possible suffixes:
- Unlike
.endswith((".tar.gz", ".zip")),str.removesuffix()accepts only a singlestr(passing atupleraisesTypeError: removesuffix() argument must be str, not tuple). Iterate through candidate suffixes in longest-first order:def strip_any_suffix(text: str, suffixes: tuple[str, ...]) -> str: for suffix in suffixes: if text.endswith(suffix): return text.removesuffix(suffix) return text print(strip_any_suffix("data.tar.gz", (".tar.gz", ".gz", ".zip"))) # Output: data
- Unlike
- Empty string argument (
text.removesuffix("")):- Passing an empty suffix
""safely returns a copy oftextunchanged (crucial if you implement a slice fallback, wheretext[:-len("")]evaluates totext[:0] == ""!).
- Passing an empty suffix
- Slice fallback for legacy Python < 3.9 (
text[:-len(suffix)]):- When supporting Python 3.8 or older, guard with
bool(suffix)before slicing:text[:-len(suffix)] if suffix and text.endswith(suffix) else text.
- When supporting Python 3.8 or older, guard with
- File paths and extensions (
pathlib.Path.stemvs..removesuffix()):- When stripping file extensions from filesystem paths,
Path("archive.tar.gz").stemonly strips the final.gz("archive.tar"), whereas"archive.tar.gz".removesuffix(".tar.gz")strips the full compound extension ("archive").
- When stripping file extensions from filesystem paths,
Comparison of Suffix-Removal Methods in Python
| Method | Matches Exact Substring? | Safe on Empty Suffix ""? |
Python Version | Best Used When |
|---|---|---|---|---|
text.removesuffix(suffix) (Recommended) |
Yes | Yes | Python 3.9+ | Removing any known literal suffix (".csv", "_old", "Controller") cleanly in C speed. |
text[:-len(suffix)] if suffix and text.endswith(suffix) else text |
Yes | Yes (with suffix and guard) |
All Python versions | Legacy Python $\le$ 3.8 codebases that cannot use .removesuffix(). |
re.sub(rf"{re.escape(suffix)}$", "", text) \vert{} Yes \vert{} Yes \vert{} All Python versions \vert{} Case-insensitive suffix stripping (flags=re.IGNORECASE) or pattern-based endings (e.g., r"_v\d+$"). |
||||
text.rstrip(chars) (Avoid for substrings) |
No (character set, not substring) | Yes | All Python versions | Stripping trailing whitespace (text.rstrip()) or repeated single characters like trailing slashes (url.rstrip("/")). |
You must log in or register to comment.
