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).