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
str.strip
Returns a copy of the string with leading and trailing whitespace removed. If chars is given, removes any leading/trailing characters that appear in the chars set (not a prefix/suffix — it is a character set).
str.lstrip
Returns a copy of the string with leading characters removed. Defaults to whitespace; a chars argument specifies a set of characters to strip from the left.
str.endswith
Returns True if the string ends with the given suffix, otherwise False. suffix may be a tuple of strings to test multiple candidates at once.
str.format
Substitutes replacement fields delimited by { } in the string with values from args and kwargs, using the Format Specification Mini-Language. In modern Python, f-strings are usually preferred for literals; str.format() remains ideal for templates loaded at runtime.
str.rjust
Returns the string right-justified in a field of the given width, padded on the left with fillchar. Returns the original string unchanged if it is already at least width characters long.