Remove Newline From String in Python

In Python, like most programming languages, newlines in strings are created with \n.

 

To remove \n from a Python string, use either the strip(), replace() or re.sub() functions. Let's have a look at how to use each of these functions with examples.

 

Python strip() Function to Remove Newlines Characters

The native Python strip() function removes both newline and whitespace characters from the beginning and end of a string.

 

test = '\nsome text\n'

result = test.strip()

print(result)
some text

 

If you just need to remove trailing newlines from a string, use the rstrip() function.

 

test = '\nsome text\n'

result = test.rstrip()

print(result)
some text

 

Remove All Newlines in a Python String

To remove all newline chars in a string, regardless of where they are located, use the native Python replace() function like this:

 

test = '\nsome\n text\n'

result = test.replace('\n', '')

print(result)
some text

 

Remove All Newlines From a List of Strings

To remove all newlines from a list of strings, iterate through each element with a for loop and append the result of replace() to a new list like this:

 

test = ['\nsome\n text\n', '\nsome\n text\n', '\nsome\n text\n']

result = []

for s in test:
   result.append(s.replace('\n', ''))

print(result)
['some text', 'some text', 'some text']