Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท String Methods

Python str.removesuffix() method

Reference for Python str.removesuffix() (3.9+): remove an exact suffix from a string if present, and how it differs from rstrip(), which removes characters.

The str.removesuffix() method returns a copy of the string without the given suffix, if the string ends with it. Otherwise the string comes back unchanged. It was added in Python 3.9.

Use it to cut a file extension, a trailing unit or a known ending. It is the safe counterpart of rstrip(), which removes characters from a set rather than a whole suffix.

Python
print("report.pdf".removesuffix(".pdf"))   # report

Try it

Python Removing a suffix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python removesuffix vs rstrip

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
str.removesuffix(suffix)
Name Description
suffix The exact string to remove from the end.

Return value: a new string. If the string does not end with suffix, the result equals the original.

Raises: TypeError if suffix is not a string.

Usage notes

  • Removes at most one copy. "a.pdf.pdf".removesuffix(".pdf") leaves "a.pdf".
  • Not rstrip(). "example.com".rstrip(".com") strips any trailing run of ., c, o and m, which happens to work here, but "mississippi".rstrip("pi") gives "mississ" instead of "mississip". Use removesuffix() for a whole suffix.
  • Empty suffix returns the string unchanged.
  • No guard needed: it is a no-op when the suffix is absent. Use endswith() when you need to know whether the suffix was there.
  • Paths: for file names, pathlib.Path("a/b.tar.gz").with_suffix("") or .stem handles the extension more safely than string tricks.
  • Before Python 3.9 write s[:-len(x)] if x and s.endswith(x) else s. Note that s[:-0] would be empty, so the empty-suffix case needs care.
  • Also available on bytes and bytearray.