str.rstrip()
Trim the right end — the go-to for removing trailing newlines from file lines.
Common call
line.rstrip("\n")
Returns
new str — original unchanged
Replaces
chars is a SET of characters, not a suffix
Watch out
rstrip("suffix") is the classic misuse — use removesuffix
str.rstrip(charschars — The set of characters to remove from the right end. None (the default) strips whitespace, including \n.type: str | None · default: None=None)
→ str
Demo
Live evaluation
Try:
Inputs
stringstrthe source
charsstrempty = whitespace
Output
'hello '.rstrip()
'hello'
Only the right end is trimmed. Note the last case: chars is a character SET — rstrip("an") keeps removing a’s and n’s, eating far more than the literal suffix "an".
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| chars | str | None | no (None) | The set of characters to remove from the right end. None (the default) strips whitespace, including \n. |
Return value
str — A new string with trailing characters removed. The start of the string is never touched.
Common patterns
Chomp line endings
The standard way to clean lines read from a file.
for line in f: process(line.rstrip("\n"))
Trim trailing slashes from URLs
Normalize before joining paths.
base = url.rstrip("/")
Examples
1. Trailing whitespace (default)
"hello ".rstrip()
Returns
'hello'2. A set of characters
"a/b///".rstrip("/")
Returns
'a/b'3. Left side untouched
" x ".rstrip()
Returns
' x'Pitfalls
1. chars is a set — not a suffix
The most-reported str "bug" on trackers: rstrip removes characters, not a substring.
Eats too much
"banana".rstrip("an")
'b'
Suffix removal
"banana".removesuffix("an")
'banan'
2. The result must be assigned
Strings are immutable — rstrip returns a new string.
Wrong
line.rstrip() process(line)
still has the newline
Fix
line = line.rstrip() process(line)
clean
When to use
Use it
- Removing trailing newlines/whitespace from lines
- Trimming trailing separators (/, ., -)
Reach for something else
- Exact suffix removal → str.removesuffix
- Both ends → str.strip
- Left end → str.lstrip
Notes
Complexity
O(n) worst case — scans from the right
Return
new str — source untouched
CPython impl
Objects/unicodeobject.c :: do_strip (RIGHTSTRIP)
Memory
One new string sized to the kept slice
Thread-safe
Yes — str is immutable
FAQ
rstrip("\n") removes ALL trailing newlines. For exactly one, use removesuffix.
line.removesuffix("\n") # at most one
History
3.9
Related: str.removesuffix added — the fix for the set-vs-suffix confusion.
2.2
chars argument added.