formatting

str.rstrip

Returns a copy of the string with trailing characters removed. Defaults to whitespace; a chars argument specifies a set of characters to strip from the right.

str.rstrip([chars])

Parameters

Parameter Purpose
chars character set to strip from the right; default is whitespace
returns new str trimmed on the right (original unchanged — str is immutable)

Examples

>>> '   hello   '.rstrip()
'   hello'

only trailing whitespace is removed

>>> 'line\n'.rstrip('\n')
'line'

commonly used to drop trailing newlines

>>> 'file.tar.gz'.rstrip('gz.')
'file.tar'

chars is a SET — removes any trailing 'g', 'z', or '.'

>>> 'hello!!!'.rstrip('!')
'hello'

strips all matching trailing chars

Gotcha

chars is a set, not a suffix. Since 3.9 prefer str.removesuffix() for literal suffix removal.

Related methods

← All Python string methods · Python built-ins