Hello Guys How Are You All? Hope You all are fine. Today in This tutorial We are going to learn About How to Remove Newline From String in Python. So lets get start this tutorial without wasting your time.
How to Remove Newline From String in Python
Remove Newline From String in Python
To Remove Newline From String in Python Use the strip() and rstrip() strip() function :This strip() function is very useful because it remove both trailing and leading newlines from the string. and it also remove the white spaces from the both side of string. Thus it is most easy method.
Input :line1 = "\n hello guys.how are you? \n" var1 = line1.strip() print(var1)
Output :hello guys.how are you?
rstrip() function :This rstrip() function only use in removing trailing newline characters. The leading newline characters are not affected by this function and it will remain the same as before. You can see this by below example:Input :line1 = "\n hello guys.how are you \n" var1 = line1.rstrip() print(var1)
Output :hello guys.how are you
Remove Newline From String in Python
To Remove Newline From String in Python use the replace() function replace() function use to remove the new line character from a string. It replace all the\n character with the help of for loop in python.
You can see this in below example. Input :list1 = ["\npizza\n", "food is \nlife", "burger\n\n "] var1 = [] for x in list1: var1.append(x.replace("\n", "")) print("New list : " + str(var1))
Output :New list : ['pizza', 'food is life', 'burger ']
Method 1 : Use the strip() and rstrip()
Use strip() function for python remove newline
This strip() function is very useful because it remove both trailing and leading newlines from the string. and it also remove the white spaces from the both side of string. Thus it is most easy method.
line1 = "\n hello guys.how are you? \n"
var1 = line1.strip()
print(var1)
Output :
hello guys.how are you?
rstrip() function :
This rstrip() function only use in removing trailing newline characters. The leading newline characters are not affected by this function and it will remain the same as before. You can see this by below example:
line1 = "\n hello guys.how are you \n"
var1 = line1.rstrip()
print(var1)
Output :
hello guys.how are you
Method 2 : use the replace() function
replace() function use to remove the new line character from a string. It replace all the\n character with the help of for loop in python. You can see this in below example.
list1 = ["\npizza\n", "food is \nlife", "burger\n\n "]
var1 = []
for x in list1:
var1.append(x.replace("\n", ""))
print("New list : " + str(var1))
Output :
New list : ['pizza', 'food is life', 'burger ']
Summary
It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you?
Also, Read