Python rstrip(): Removing Trailing Whitespace and Characters
Learn how Python's rstrip() method removes trailing whitespace and specific characters from strings, with practical examples and common pitfalls.

When you need to remove trailing characters from the end of a string, Python's rstrip() method is the tool to use. It returns a new string with trailing whitespace or a specified set of characters removed, leaving the original string unchanged. This is essential when cleaning data read from files, user input, or network payloads.
What rstrip() Does and When to Use It
rstrip() is a built-in string method that returns a copy of the string with trailing characters removed. Because Python strings are immutable, the original string is not modified. You typically use it when you need to normalize data before further processing, such as removing a trailing newline from a line read from a file or trimming spaces from a form field.
rstrip() Without Arguments: Removing Trailing Whitespace
When called with no arguments, rstrip() removes all trailing whitespace characters. This includes spaces, tabs, newlines, carriage returns, and any other character that Python's str.isspace() method considers whitespace.
line = " hello world \n"
cleaned = line.rstrip()
print(repr(cleaned)) # ' hello world'Notice that leading whitespace is preserved. Only the right side of the string is affected. This is useful when the leading spaces carry meaning, such as in indented text or aligned columns.
Passing Characters to rstrip(): Removing Specific Trailing Characters
You can pass a string argument to rstrip() to specify a set of characters to remove. The method removes any trailing character that appears in that set. It does not treat the argument as a literal suffix to remove.
filename = "data.txt"
stripped = filename.rstrip(".txt")
print(stripped) # 'data'Here ".txt" is interpreted as a set containing ., t, and x. So rstrip() removes any trailing characters that are in that set. For data.txt, this produces data, but the behavior is easy to misread. If the filename ends with one of those characters before the extension, it will be removed too:
filename = "report.txt"
print(filename.rstrip(".txt")) # 'repo', not 'report'Because report.txt ends with t before the dot, that t is also part of the character set, so rstrip() removes it.
How rstrip() Interprets the Characters Argument
The argument to rstrip() is a set of characters, not a suffix. This distinction is a common source of bugs. Consider this example:
url = "https://example.com/"
print(url.rstrip("/")) # 'https://example.com'That works as expected because only the slash is removed. But look at this:
name = "python"
print(name.rstrip("on")) # 'pyth'Both o and n are in the set, so they are removed from the end. If you need to remove a specific suffix, use removesuffix() (available in Python 3.9 and later) or check endswith() before slicing manually.
Common Pitfalls: Newlines, Indentation, and Unexpected Removals
A frequent mistake is using rstrip() to remove a trailing newline but accidentally stripping spaces that are part of the data. For example, if a line ends with meaningful spaces, rstrip() without arguments will remove them. Similarly, passing a multi-character string to rstrip() thinking it removes that exact suffix can silently corrupt data if the string ends with one of those characters for a different reason.
Another pitfall involves Windows line endings. A file written on Windows may end lines with \r\n. Calling rstrip() without arguments removes both, but if you pass only "\n", the carriage return remains. You need to pass "\r\n" to handle both characters.
rstrip() vs. strip() and lstrip(): Choosing the Right Method
Python provides three related methods: rstrip(), lstrip(), and strip(). The choice depends on which side of the string you need to clean.
| Method | Removes from | Typical use |
|---|---|---|
rstrip() | Right end | Remove trailing newline or spaces |
lstrip() | Left end | Remove leading indentation |
strip() | Both ends | Clean user input |
Use rstrip() when you only care about the end of the string, such as when processing lines from a file where leading whitespace is significant. Use lstrip() for the opposite case, and strip() when you need to clean both sides.
Performance and Memory Behavior of rstrip()
rstrip() returns a new string when it removes characters; it never modifies the original. Because strings are immutable, building that new string has a cost. For most use cases, the cost is negligible. However, if you call rstrip() in a tight loop over a large number of strings, the repeated allocations can add up. In such scenarios, consider processing data in a way that avoids creating intermediate strings, or use a generator that yields cleaned strings lazily.
There is no in-place modification, so memory usage scales with the size of the cleaned string. The original string remains in memory until it is garbage collected. This is usually not a concern unless you are holding many large strings simultaneously.
Using rstrip() in Real-World Text Processing
A typical pattern is reading a file line by line and stripping trailing newlines before parsing:
with open("data.txt") as f:
for line in f:
cleaned = line.rstrip("\n")
# process cleanedHere we pass "\n" to remove only the newline, preserving any trailing spaces that might be part of the data. If the file uses Windows line endings, you need to remove both characters:
cleaned = line.rstrip("\r\n")This removes any trailing combination of carriage return and newline. When working with CSV or log files, rstrip() is often combined with split() to parse fields. Just be aware of the character-set behavior when passing a string argument, and test with your actual data to avoid removing characters that are meaningful.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.