W3docs

How can I remove a trailing newline?

To remove a trailing newline from a string in Python, you can use the rstrip() method.

To remove a trailing newline from a string in Python, you can use the rstrip() method. This method returns a copy of the string with the trailing whitespace removed. For example:

Remove a trailing newline from a string in Python

string = "Hello World!\n"
string = string.rstrip()
print(repr(string))  # Output: "Hello World!"

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

You can also use the strip() method to remove both leading and trailing whitespace from a string.

Remove both leading and trailing whitespace from a string in Python

string = "   Hello World!   \n"
string = string.strip()
print(repr(string))  # Output: "Hello World!"

If you want to remove only the trailing newline, you can use the rstrip() method as shown above. If you want to remove other types of whitespace, such as leading or trailing spaces, you can pass the characters you want to remove as an argument to the strip() or rstrip() method. For example:

Remove a custom leading or trailing character from a string in Python

string = "   Hello World!   \n"
string = string.rstrip(" \n")
print(repr(string))  # Output: "   Hello World!"

This removes the trailing newline and any trailing spaces from the string.