Remove trailing newlines from a Python string
Choose rstrip or removesuffix based on whether you want to remove all trailing newline characters, one line ending, or every kind of whitespace.
Use text.rstrip("\n") to remove all trailing newline characters. Use text.removesuffix("\n") in Python 3.9 or later to remove exactly one. Plain rstrip() removes all trailing whitespace, including spaces and tabs.
Choose what to remove
text = "report \n"
print(repr(text.rstrip("\n"))) # 'report '
print(repr(text.rstrip())) # 'report'
print(repr(text.removesuffix("\n"))) # 'report '
These methods return a new string; they do not modify the original. repr() makes retained whitespace visible in the output.
Multiple newlines show the difference between a character set and a single suffix:
text = "report\n\n\n"
print(repr(text.rstrip("\n"))) # 'report'
print(repr(text.removesuffix("\n"))) # 'report\n\n'
Clean lines from a text file
with open("file.txt", encoding="utf-8") as source:
for line in source:
cleaned = line.removesuffix("\n")
print(cleaned)
The final line may not have a newline; removesuffix leaves it alone. Default text-mode universal newline handling translates \r\n and \r line endings to \n before your code sees them.
Handle raw Windows line endings
For text that still contains CRLF, text.rstrip("\r\n") removes any run of those characters at the end. If you need to remove exactly one recognized line ending, handle the two-character ending first:
def remove_line_ending(text):
if text.endswith("\r\n"):
return text[:-2]
if text.endswith(("\n", "\r")):
return text[:-1]
return text
This preserves additional blank-line endings rather than stripping them all.
FAQ
How do strip, lstrip, and rstrip differ? They remove matching characters from both ends, the left end, and the right end respectively. Without an argument they remove whitespace. Use strip() only when leading whitespace is also disposable.
Does rstrip("ab") remove the suffix ab? It removes any trailing combination of a and b. Use removesuffix("ab") for one exact suffix.
What about a trailing comma? rstrip(",") removes all trailing commas; removesuffix(",") removes at most one.
References
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan