How To Strip New Line In Python?

Text files use the new line in order to jump into the next line. The new line is expressed with the “\n” characters in general. These new line characters can be removed in different ways in Python. In this tutorial, we will examine how to remove trailing lines or strip new lines in Python.

Strip New Line with strip() Method

Python string variables or type provides some methods which can be used to manipulate the string data. The strip() method is used to remove or strip the specified characters from the current string. The strip() method can be used to strip a new line in a string.

text = "I like python \n I like python \n I like python"

text.strip("\n")

Strip New Line with rstrip() Method

The rstrip() is a bit different version of the strip() method. The rstrip() strip from right and can be used to strip new line.

text = "I like python \n I like python \n I like python"

text.rstrip("\n")

Strip New Line with lstrip() Method

Another alternative to strip the new line is the lstrip() method. The lstrip() method is the left version of the rstrip() method.

text = "I like python \n I like python \n I like python"

text.lstrip("\n")

Strip New Line with replace() Method

The Python string type also provides the replace method. The replace() method is used to replace the specified characters with the specified characters. So we can replace the new line with an empty string in this case.

text = "I like python \n I like python \n I like python"

text.replace("\n","")

Leave a Comment