String method

str.rstrip()

Removes whitespace, or any characters you list, from the end (right side) of a string, such as the new line at the end of a line.

BeginnerEvery example below runs in your browser. Change the code and press Run.

str.rstrip(chars=None)

rstrip() is str.strip() for the right side only: it removes spaces, tabs and new lines from the end of a string. The "r" stands for right.

Its most common job is reading files: every line you read ends in \n, and line.rstrip("\n") removes it while keeping any spaces at the start that may matter, such as indentation.

The argument is a set of characters, not a word, so "basics.csv".rstrip(".csv") removes too much. Use str.removesuffix() to remove an exact ending such as a file extension.

Parameters

ParameterWhat it is
chars
optional, default None
The characters to remove from the end, as one string. Order does not matter. With None, whitespace is removed.

Return value

A new string without those characters at the end.

Examples

1Remove the new line at the end

Pythoneditable
line = "Hello\n"
print(repr(line))
print(repr(line.rstrip()))
Output
'Hello\n'
'Hello'

repr() shows the string with its quotes and hidden characters, so you can see the \n.

2Read a file line by line

Pythoneditable
with open("names.txt") as f:
    for line in f:
        print(line.rstrip("\n") + "!")
Output
Ana!
Omar!
Yuki!

Without rstrip(), the ! would appear at the start of the next line.

3Remove trailing zeros from a number written as text

Pythoneditable
print("12.500".rstrip("0"))
print("12.000".rstrip("0").rstrip("."))
Output
12.5
12

4Remove trailing punctuation

Pythoneditable
question = "Are you sure?!?"
print(question.rstrip("?!"))
Output
Are you sure

Common mistakes

Using rstrip() to remove a file extension

The characters ., c, s and v are removed one by one from the end, so the s and c of basics go too. removesuffix() removes the exact text.

Pythoneditable
filename = "basics.csv"
print(filename.rstrip(".csv"))
print(filename.removesuffix(".csv"))
Output
basi
basics

Questions people ask

rstrip() vs rstrip("\n"): which one for file lines?

rstrip() also removes spaces and tabs at the end. If trailing spaces matter in your data, use rstrip("\n") to remove only the new line.

How do I remove a file extension?

Use name.removesuffix(".csv"), or name.rsplit(".", 1)[0] for any extension.

Does rstrip() remove spaces in the middle?

No. It stops at the first character from the right that is not in the list.

Spotted a mistake on this page? Tell us