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().
print("hello \n".rstrip() + "|") # hello|
Try it
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.
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
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,oandm. That happens to give the right answer here, but"file.tar.gz".rstrip("gz")leaves"file.tar."with a stray dot. Preferremovesuffix()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, whileline.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 withformat()instead. - Original is unchanged. Strings are immutable.
- Both ends:
strip(); leading only:lstrip(). - Also on
bytesandbytearray.