Hurry! Try our new Interactive Courses for FREE. 🥳   🚀
  Signup/Sign In

How to Remove trailing newlines in Python

In this article, we will learn how to eliminate trailing newline from a string in Python. We will use some built-in functions, simple approaches available in Python.

Python strings contain a newline ('\n') character. Sometimes, we have a large volume of data and we need to perform some preprocessing and we might need to remove newline characters from strings. If you want to remove only trailing newline, use rstrip() function else you can use other mentioned functions such as strip(), brute force approach, and re.sub(). Let us look at these ways.

Example: Remove Trailing Newline Using rstrip() Function

The rstrip() means stripping or removing characters from the right side. It removes trailing newlines as well as whitespaces from the given string. Leading newlines and whitespaces are retained. We call string.rstrip() on a string with "\n" to create a new string with the trailing newline removed.

#original string
string1 = "   \n\r\n  \n  abc   def \n\r\n  \n  "

new_string = string1.rstrip()

# Print updated string
print(new_string)





abc def

Example: Remove Trailing Newline Using strip() Function

The strip() means stripping or removing characters from both sides. It removes trailing as well as leading newlines and whitespaces from the given string.

#original string
string1 = "   \n\r\n  \n  abc   def \n\r\n  \n  "

new_string = string1.strip()

# Print updated string
print(new_string)


abc def

Example: Remove Trailing Newline Using replce() Function

This example uses for loop and replace(). We check for “\n” as a string in a string and replace that from each string using the loop.

#original list 
list1 = ["this\n", "i\ns", "list\n\n "] 

res = []

for x in list1:
    res.append(x.replace("\n", ""))

print("New list : " + str(res))


New list : ['this', 'is', 'list ']

Example: Remove Trailing Newline Using Regex

This example uses re.sub() function of regex module. It performs a global replacement of all the newline characters with an empty string. The brute force approach just removes one occurrence while this method checks for every occurrence.

#original list
list1 = ["this\n", "i\ns", "list\n\n "] 

res = []

for sub in list1:
    res.append(re.sub('\n', '', sub))

print("New list: " + str(res))


New list: ['this', 'is', 'list ']

Conclusion

In this article, we learned multiple ways to remove trailing newlines from a string in Python. The user needs to keep in mind that to remove only trailing newlines, make use of rstrip() function. Other methods like strip(), using loop and replace, and re.sub() removes all newlines and whitespaces whether they occur on the right side, in the middle, or on the left side.