Remove Newline Characters from a String in Python

When I was working on a project for my clients, I often ran into newline characters that broke my workflow. Sometimes I was processing CSV files exported from Excel, and the text fields had hidden \n characters.

Other times, I was cleaning up scraped web data where newlines made everything messy. If you’ve ever tried to join text into one clean line, you know how frustrating it can be when newlines sneak in.

In this tutorial, I’ll show you the most practical Python methods to remove newline characters from a string. I’ll explain each method with simple examples, so you can pick the one that works best for your use case.

Methods to Remove Newline Characters from a String in Python

Let me explain to you the methods to remove newline characters from a string in Python.

Suppose there is a string that contains newline characters like this,

string = "\n The United States of America (USA),\n is a country primarily located in North America\n."

So, we can see so many new line (\n) characters in the string, which are used to break the line in Python. But we need to remove the new lines from the string to get this type of output,

The United States of America (USA), is a country primarily located in North America.

Let’s examine step-by-step all the methods for removing a new line from a string in Python, with some practical examples.

Method 1: Use strip() Method in Python

I will use the Python strip() method to remove the newline from the string. Generally, this method eliminates the character or whitespace from the first and last index only.

Syntax

string.strip("\n")
  • string.strip(“\n”): If you don’t give any parameter in the strip() method, it will remove the white space by default, if it exists, from the string.
headline = "\nBreaking News: Major Event in Central Park!\n"
print('Before Modifictions :', headline,"\n")

clean_headline = headline.strip('\n')

print('After: ', clean_headline)

You can see the output in the screenshot below.

Python Remove newline from string using strip() method

I have given a new line character at the start and end of the string, so it properly removes the new line from the string headline.strip(‘\n’).

Method 2: Use Python’s replace() Method

What if we need to remove the new line from everywhere in the string? So, we can use the replace() method, which replaces all occurrences of any character in the string.

Syntax

str.replace(old_pattern, new_pattern)
  • str.replace(old_pattern, new_pattern): In the syntax, we can give “\n” as an old pattern and an empty string as a new pattern. This targets all the ‘\n’ characters from the string and replaces them with the empty string.
review = "The food was amazing.\nThe service was top-notch.\nWill visit again!"
print('Before:\n', review,"\n")
after_cleaning = review.replace("\n", " ")
print('After:\n', after_cleaning)

You can see the output in the screenshot below.

Remove newlines from string Python using the replace() method

I have a string named review, where multiple \n characters exist, and I want to replace all of them. So I am using the replace() method, like this: “after_cleaning = review.replace(“\n”, ” “)”, which will replace all the \n characters with the empty string.

Method 3: Use split() and join() Method in Python

This is not the direct way to remove newlines, but it can give the required output by combining the split() and join() methods.

Syntax

" ".join(string.split('\n'))
  • We will use this syntax to remove a new line from the Python string.
  • split(‘n’): This function creates a list and separates the string based on the given pattern.
  • .join(): This method will concatenate the elements from the list to a string.
paragraph = "It was a bright day in Dallas.\nThe sun was shining, and people were happy.\nLife was good.\n"

print('With New Line:\n', paragraph)

clean_paragraph = ''.join(paragraph.split('\n'))
print('Without New Line:\n', clean_paragraph)

You can see the output in the screenshot below.

Python Remove newline from the middle of string using split() and join() method

I have a string named paragraph, and I need to remove a newline from the string. So first, I created an empty string and then used the split() method with \n as a parameter so that it would make a list separated by the \n character, like this: “It was a bright day in Dallas. The sun was shining”.

Method 4: Use the splitlines() Method

I can also use the splitlines() method of Python. It is similar to the split() method, but will directly target the new line characters from the string.

Syntax

" ".join(string.splitlines())
  • string.splitlines (): There is no need to give it any parameters because it targets all the new line characters by default.
message =  "\n The United States of America (USA),\n is a country primarily located in North America.\n"

print("Before:",message, "\n")
result = "".join(message.splitlines())
print("After: \n",result)

You can see the output in the screenshot below.

Remove the newline from the string in Python using the splitlines() method

I have used the splitlines() method to remove a new line from the Python string. I will use the same logic I’ve used in the previous example, but the difference is that you don’t need to give any parameter to target new line characters.

Method 5: Use Python Regex

The sub() method of the ‘re’ module replaces the pattern in the string. The same logic will be applied as we’ve used in the replace() method.

Syntax

re.sub('old_pattern', 'new_pattern', string)
import re

message = "\nThe United States\n is a founding member of \n the United Nations"
print("Before:" + message+"\n")

new_message = re.sub('\r?\n', '', message)
print("After: \n" + new_message)

You can see the output in the screenshot below.

Python Remove newline from string using Regex

I have a string that contains multiple newline characters to make it a one-line string. So, I am using the re.sub() method like this: ” re.sub(‘\r?\n’, ”, message)”, which will replace the pattern as we’ve used in the replace method.

Conclusion

In this Python article, I helped you to learn how to remove newline characters from a string using five different methods, such as the strip() method, the replace() method, the join() and split() methods, and the re.sub() method.

I’ve also explained the scenario so you can understand more clearly where to use those Python methods.

You may also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.