How can I remove a trailing newline?
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:
string = "Hello World!\n"
string = string.rstrip()
print(repr(string)) # Output: "Hello World!"
Watch a video course
Python - The Practical Guide
You can also use the strip()
method to remove both leading and trailing whitespace from a string.
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:
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.