This guide explains str.rstrip Method: Usage and Examples through a focused example and practical reasoning. No prior knowledge of this specific operation is required.
Understanding the Concept
str.rstrip(chars=None) removes trailing whitespace by default. If characters are supplied, it removes trailing characters belonging to that set, not a literal suffix.
When You Would Use This
Clean trailing spaces and newlines from a text record.
Step-by-Step Example
raw_status = "Ready \n"
print(repr(raw_status.rstrip()))
print("status.txt".rstrip(".txt"))
How the Example Works
The first result is Ready. The second demonstrates a potential surprise because .rstrip(".txt") removes matching trailing characters repeatedly rather than only the exact suffix.
Example Output
'Ready'
status
Try It Yourself
Use .removesuffix(".txt") when the goal is to remove an exact filename extension.
Common Beginner Mistakes
- Using
.rstrip(".txt")to remove a filename extension. - Assuming leading whitespace is also removed.
- Forgetting that a newline at the end of a file may be significant.
Key Takeaways
str.rstrip(chars=None)removes trailing whitespace by default.- The first result is
Ready. - Avoid this mistake: Using
.rstrip(".txt")to remove a filename extension.