How to remove newline from Strings in Python?

In Python, \n  represents a newline character. They are also called line breaks. They are used to indicate the end of the current line.

When you’re processing the input files for data cleaning, the first step is to remove the extra spaces and unnecessary newline characters from the lines. At times, you might also want to remove the new line character while printing strings.

In this article, we will be addressing the following cases:

  • Removing new line characters from a string.
  • Removing newline characters from a list of strings.
  • Removing newline characters while printing a list of strings.

Removing newline characters from a string while processing.

Now, consider a string as shown below:

my_str="\nLet's remove newline character from the string\n"

The my_str string has newline characters at the beginning and the end.

 

Removing trailing newline characters using lstrip()

To remove the newline character at the beginning of a string, you can use the lstrip() function as shown below.

my_str="\nLet's remove newline charcter from the string\n"
print(my_str.lstrip())

Output:

Let's remove newline charcter from the string


Process finished with exit code 0

Note that the newline character at the beginning of the string has been removed by the lstrip() function. However, the newline character at the end is still present. Note that the output shows two new lines at the end. One is add

 

Removing leading newline characters using rstrip()

You can also use the rstrip() function to remove the new line character(s) at the end of the string. Check the code below for more details.

my_str="\nLet's remove newline charcter from the string\n"
print(my_str.rstrip())

Output:

Let's remove newline charcter from the string

Process finished with exit code 0

As seen from the above output, the nextline character at the end of the string is removed. Note that the output shows one newline character in the output. This is added by the print() function.

 

Removing both the trailing and leading newline characters using strip()

To remove both the trailing and leading spaces from the string, you can use the strip() function as shown below. This removes any extra spaces and new line characters from the beginning and end of the string.

my_str="\nLet's remove newline charcter from the string\n"
print(my_str.strip())

Output:

Let's remove newline charcter from the string

Process finished with exit code 0

Removing newline characters from a string using str.replace()

One can also use the built-in replace() function. This replaces any occurrence of the specified character with some other character. We can replace the newline character(\n) with an empty character in the strings.

Consider the following example.

my_str="\nLet's remove\n newline charcter\n from the string\n"
print(my_str.replace("\n",""))

Output:

Let's remove newline charcter from the string

Removing newline characters from a string using re.sub()

The regex module in python enables you to use the re.sub() function to replace an expression with another expression. To use this module, firstly we have to import it using the following command:

import re

Now, we search for the occurrences of newline character(\n) and replace it with the empty character with re.sub() as shown below

import re

my_str="\nLet's remove\n newline charcter\n from the string\n"
print(re.sub("\n","",my_str))

Output:

Let's remove newline charcter from the string

Removing newline characters from a string using str.splitlines() and join()

You can also use the built-in function splitlines() on the string to split the string based on the newline character. The output will be a list object. You can merge this list back to a string using the join() function.

my_str="\nLet's remove\n newline\n charcter\n from the string\n"
print("".join(my_str.splitlines()))

Output:

Let's remove newline charcter from the string

 

Removing newline characters while printing a list of strings

Let’s say, you have a list as shown below and you want to print it over a loop.

lst=["Let's", 'remove', 'newline', 'charcter', 'from', 'the', 'string']
for item in lst:
    print(item)

By default, the print() function adds a newline character at the end of every string. Refer to the output below.

Let's
remove
newline
charcter
from
the
string

If you want to remove the newline characters and have space while printing the above string, pass the parameter end=” ” with the print function as shown below.

lst=["Let's", 'remove', 'newline', 'charcter', 'from', 'the', 'string']
for item in lst:
    print(item,end=" ")

Output:

Let's remove newline charcter from the string

 

Removing newline characters from a list of strings.

Consider a list of strings as shown below. The list contains a few strings with newline characters.

lst = ["\nLet's","remove\n","newline\n","charcter\n from the","string\n"]

 

If you want to remove the newline characters from all of these strings, iterate over the list and then remove the newline characters as shown below.

lst_with_newline = ["\nLet's","remove\n","newline\n","charcter\n from the","string\n"]
lst=[]

for item in lst_with_newline:
    lst.append(item.replace("\n",""))

print(lst)

Output:

["Let's", 'remove', 'newline', 'charcter from the', 'string']

 

Alternatively, you can use the map() function to make the changes as shown below

lst_with_newline = ["\nLet's","remove\n","newline\n","charcter\n from the","string\n"]

def replace_newline(s):
    return s.replace("\n","")

print(list(map(replace_newline,lst_with_newline)))

Output:

["Let's", 'remove', 'newline', 'charcter from the', 'string']

Explanation:

In the above code snippet, the replace_newline function is called on every string object of the list. This function removes any newline characters from the strings.

Conclusion:

In this article, we’ve discussed different ways of removing the new line characters from the string, a list of strings, and while printing strings. To summarize,

  • Use lstrip() – to remove the trailing nextline characters.
  • Use rstrip() – to remove leading nextline characters.
  • Use strip() – to remove both the trailing and leading nextline characters.
  • Use replace() , re.sub() – to remove the newlines from anywhere in the string
  • Change the default value of end=”\n” in the print() function to remove the nextline character from being printed at the end of the string.
  • When you list of strings from which new lines have to be removed, iterate over the string object using for loop or map() and then remove the newlines.

We hope this article has been informative.

Thanks for reading.

 

Also check, How to check if a file exists in Python without exceptions?

 

 

If you enjoyed reading, share this article.

Anusha Pai is a Software Engineer having a long experience in the IT industry and having a passion to write. She has a keen interest in writing Python Errorfixes, Solutions, and Tutorials.

Leave a Comment