How To Remove \n From String In Python

How do you remove a newline character \n from a string in Python?

The easiest way to remove a new line from a string in Python is by using the string method .replace() . Another way is to use the string method .strip() if the new line is at the start or end of the string.

Here are some examples demonstrating how to remove the new line characters:

>>> s = """
... This string has new lines
... everywhere!
... """
>>> print(s)

This string has new lines
everywhere!

>>> s.replace('\n', '')
'This string has new lineseverywhere!'

As you can see from the above output the string .replace() method takes two parameters: the first being the string to find and the second being the string to replace once found.

The new line character in Python is the string \n , therefore, in the string .replace() method the first parameter is this new line string \n and the second parameter is what you would like to replace it with.

In the example above I am replacing the new line string with an empty string which means all new line strings found in my original string are removed.

However, this did present a problem with the result. Did you notice that the final string didn’t insert a space between the words lines and everywhere ?

This can be a problem with the .replace() string method, it will perform the replacement on all occurrences of the string when found in the original string.

If I wanted to remove the trailing and leading new line characters from my original string I can use another built-in string method called .strip() .

Here is how this method could help with the original string:

>>> s = """
... This string has new lines
... everywhere!
... """
>>> print(s)

This string has new lines
everywhere!

>>> s.strip()
'This string has new lines\neverywhere!'

As you can see from running the same code but instead using the .strip() method I have been able to remove the leading and trailing new lines from my original string.

You will also notice the new line character embedded between the words lines and everywhere . The .strip() method only operates on leading and trailing characters in a string – not those found elsewhere.

To achieve the intended result of removing trailing and leading new lines and converting new lines found in the middle to spaces you can chain both the .strip() and .replace() string methods together.

You just need to do so in the correct order! As seen below:

>>> s = """
... This string has new lines
... everywhere!
... """
>>> print(s)

This string has new lines
everywhere!

>>> s.strip().replace('\n', ' ')
'This string has new lines everywhere!'

You can also be quite selective on the type of stripping you want to perform on your original string.

Besides the .strip() string method which strips all leading and trailing whitespace characters from a string there are similar string methods which only strip the left side of the string .lstrip() or right side .rstrip() .

Here is a demonstration of these other strip methods with the original string:

>>> s = """
... This string has new lines
... everywhere!
... """
>>> print(s)

This string has new lines
everywhere!

>>> s.rstrip()
'\nThis string has new lines\neverywhere!'
>>> s.lstrip()
'This string has new lines\neverywhere!\n'

Using Regex sub

Another alternative to the .strip() and .replace() string methods is to use the regex library’s method sub() which is short for substitute.

The Regex library can help to enable more acute removal of new lines if only certain specific new line characters need to be changed.

For example, perhaps if the new line character is found at the end of a sentence you would want to retain it, but if not to replace it with a space character.

Here is how this could look using the Regex .sub() function:

>>> from re import sub
>>> s = """
... This is a sentence.
... Don't touch new lines
... at the end of a sentence.
... Ok?
... Got it!
...
... """
>>> sub(r'^\n|\n$|[^.]\n', ' ', s)
"This is a sentence.\nDon't touch new lines at the end of a sentence.\nOk? Got it! "

As you can see the sub() Regex function works well. The Regex pattern found in the first parameter of the function finds any new line characters at the start of the string ^\n ; any new line characters at the end of the string \n$ ; and any new line character string that isn’t preceded by a full-stop [^.]\n .

You could further refine the Regex pattern to exclude the removal of new line characters when the new line character is found after a question mark or exclamation mark. This would mean making an addition to the Regex pattern, so that it would look like this:

sub(r'^\n|\n$|[^.!?]\n', ' ', s)

Another aspect when using the Regex library that can further enhance how you want to handle new line characters is whether you want to capture a specific quantity of new lines.

Regex enables users to only apply certain captures according to the number of instances found.

Take for example the following string which deliberately contains one new line character, two adjoining new line characters, and three adjoining new line characters:

>>> from re import sub
>>> s = """
... One new line.
...
... Two new lines.
...
...
... Three new lines."""
>>> s
'\nOne new line.\n\nTwo new lines.\n\n\nThree new lines.'
>>> sub(r'\n{2,3}', '\n', s)
'\nOne new line.\nTwo new lines.\nThree new lines.'

As you can see from the above example, by appending {start_num,stop_num} after the new line string character you can specify how many consecutive new line characters you want to capture and change.

Another alternative is to use the + symbol which means capture all instances of one or more new line characters and would be written as \n+ .

Summary

To remove new line characters from a string use the string methods .replace() when seeking to replace every new line character with something, or .strip() when trying to remove just the leading or trailing new line characters from a string, or the Regex library’s .sub() function to remove specific new line characters found before or after certain characters, or even a number of consecutive new line characters together.

Photo of author
Ryan Sheehy
Ryan has been dabbling in code since the late '90s when he cut his teeth exploring VBA in Excel. Having his eyes opened with the potential of automating repetitive tasks, he expanded to Python and then moved over to scripting languages such as HTML, CSS, Javascript and PHP.