Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท String Methods

Python str.rstrip() method

Reference for Python str.rstrip(): remove trailing whitespace or any characters from a set, why it is not removesuffix(), and common newline uses.

The str.rstrip() method returns a copy of the string with trailing characters removed. With no argument it removes whitespace (spaces, tabs, newlines and other Unicode whitespace). With an argument, it removes any trailing characters that appear in that argument.

The argument is a set of characters, not a suffix. That surprises many people, so for removing a whole ending use removesuffix().

Python
print("hello  \n".rstrip() + "|")   # hello|

Try it

Python Trailing whitespace and characters

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 A set of characters, not 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.

Syntax

Python
str.rstrip()
str.rstrip(chars)
Name Description
chars Optional. A string whose characters are all removed from the end, in any order and any number. None or omitted means whitespace.

Return value: a new string.

Raises: TypeError if chars is neither a string nor None.

Usage notes

  • Characters, not a suffix. "example.com".rstrip(".com") removes any trailing run of ., c, o and m. That happens to give the right answer here, but "file.tar.gz".rstrip("gz") leaves "file.tar." with a stray dot. Prefer removesuffix() for exact endings.
  • Stops at the first character not in the set, so interior characters are never touched.
  • Newlines: line.rstrip("\n") removes only newlines, while line.rstrip() removes all trailing whitespace, including spaces you may want to keep.
  • Trailing zeros on a number string: "100".rstrip("0") gives "1", which is a classic bug. Format numbers with format() instead.
  • Original is unchanged. Strings are immutable.
  • Both ends: strip(); leading only: lstrip().
  • Also on bytes and bytearray.