Python | Removing newline character from string
Many times, while working with Python strings, we can have a problem in which we have a huge amount of data and we need to perform preprocessing of a certain kind. This can also be removing stray newline characters in strings. Let’s discuss certain ways in which this task can be performed.
Here, we will cover 4 different methods to Remove Newline From String in Python:
- Using the replace() function
- Using the strip() function
- Using splitlines() method
- Using the re.sub() Function
Method 1: Use the replace function to Remove a Newline Character From the String in Python
This task can be performed using brute force in which we check for “\n” as a string in a string and replace that from each string using a loop.
Python3
# initialize listtest_list = ['gf\ng', 'i\ns', 'b\nest', 'fo\nr', 'geeks\n']# printing original listprint("The original list : " + str(test_list))# Removing newline character from string# using loopres = []for sub in test_list: res.append(sub.replace("\n", ""))# printing resultprint("List after newline character removal : " + str(res)) |
Output :
The original list : ['gf\ng', 'i\ns', 'b\nest', 'fo\nr', 'geeks\n'] List after newline character removal : ['gfg', 'is', 'best', 'for', 'geeks']
Method 2: Use the strip() Function to Remove a Newline Character From the String in Python
The strip() method in-built function of Python is used to remove all the leading and trailing spaces from a string. Our task can be performed using strip function() in which we check for “\n” as a string in a string.
Python3
lis = "\n Geeks for Geeks \n"string = lis.strip()print(string) |
Output:
Geeks for Geeks
Method 3: Use the splitlines() method to Remove a Newline Character From the String in Python
Python String splitlines() method is used to split the lines at line boundaries. The function returns a list of lines in the string, including the line break.
Python3
def func(value): return ''.join(value.splitlines())mystring = "\n Geeks \n for \n Geeks \n"print("Original string:", mystring)print("After deleting the new line:", func(mystring)) |
Output:
Actual string: Geeks for Geeks After deleting the new line: Geeks for Geeks
Method 4: Use the re.sub() Function to Remove a Newline Character From the String in Python
This task can also be executed using regex functions which can also perform the global replace of all the newline characters with an empty string.
Python3
import re# initialize listtest_list = ['gf\ng', 'i\ns', 'b\nest', 'fo\nr', 'geeks\n']# printing original listprint("The original list : " + str(test_list))# Removing newline character from string# Using regexres = []for sub in test_list: res.append(re.sub('\n', '', sub))# printing resultprint("List after newline character removal : " + str(res)) |
Output :
The original list : ['gf\ng', 'i\ns', 'b\nest', 'fo\nr', 'geeks\n'] List after newline character removal : ['gfg', 'is', 'best', 'for', 'geeks']


