Remove Newline From String In Python

In this tutorial, I will show you different techniques for how to remove newline from string in python. So without wasting any further time. Let’s get started.

In python, the string characters starting with backslash “\” are special characters called escape characters and where ‘\n’ represents new line and ‘\t’ represents the tab character.

1. By Using replace() method

In the below code, we have used the replace method of python string to substitute all the newline characters from the input string with the empty string.

#1 program to remove newline from string in python

# input string containing new line chars
string = "\nHello \n World"

# Use replace method to replace \n
newstring = string.replace("\n","")
print(newstring)

Here is the output of the above code.

Output :

Output of the program to remove newline from string in python by using replace

2. By Using regex

regular expression is a special sequence of characters that are used to match or find other strings by using a specialized syntax. Python provides re module to work with the regular expressions.

Below is the special regular expression to remove newline from string in python.

import re

string = "\nHello \n World" # input string
#use regular expression to remove newline from string in python
new = re.sub("\n","",string)
print(new)

3. Remove Trailing New Line Characters

The strip() method of the python string removes the trailing white space from it.

Note: it only removes from the start and end of the string, not from the middle.

# string with trailing white space
string = "\n\n \n   Hello \n World \n \n    " 
print(string.strip())

Output :

'Hello \n World'

4. By Using For-Loop

In this code example, we have used for loop to remove new line from string.

Here is the algorithm.

  • We first define an empty string to store the result.
  • Then we iterate through each character of the string.
  • On each iteration, we check if the character is not equal to the new line then we add it to the result string.
string = "\nHello \n World" # input string

newstring = "" # new empty string

for i in string: # iterate through the string
    if i != "\n": # check if char is not new line
        newstring += i # add this to newstring

print(newstring)

Also read about how to remove a character from string in python.

Leave a Reply