How do I remove a trailing newline in Python?

Better Stack Team
Updated on February 3, 2023

You can use the rstrip() method to remove a trailing newline from a string. Here is an example:

 
s = "Hello, World!\n"
s = s.rstrip()
print(s)

This will print "Hello, World!" (without the newline).

Alternatively, you can use the strip() method to remove both leading and trailing whitespace, including newlines. For example:

 
s = "   Hello, World!\n"
s = s.strip()
print(s)

This will also print "Hello, World!" (without the leading spaces or the newline).

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →