python remove newline – How to remove a trailing newline in Python?

python remove newline Use the strip() Function, Use the replace() Function and Use the re.sub() Function to Remove a Newline Character From the String in Python Example with demo.

python remove newline

python remove newline : Remove Newline From String in Python

Use the strip() Function to Remove a Newline Character From the String in Python

Example

userinput = "\n Tamilrokers has the useful website \n"
newstr = userinput.strip()
print(newstr)

Result

Tamilrokers has the useful website

Use the replace() Function to Remove a Newline Character From the String in Python

Example 1:

userinput = "\n Tamilrokers has the useful website \n"
newstr = userinput.rstrip()
print(newstr)

Result

Tamilrokers has the useful website

Example 2:

userinput = ["Tamilrokers\n", "has the \nuseful", "website\n\n "]
rez = []

for x in userinput:
    rez.append(x.replace("\n", ""))

print("New list : " + str(rez))

Result

New list : ['Tamilrokers', 'has the useful', 'website ']

Don’t Miss : Python Remove Newline From String

Use the re.sub() Function to Remove a Newline Character From the String in Python

Example

#import the regex library
import re

userinput = ["Tamilrokers\n", "has the \nuseful", "website\n\n "]
  
rez = []
for sub in userinput:
    rez.append(sub.replace("\n", ""))
          
print("New List : " + str(rez))

Result

New List : ['Tamilrokers', 'has the useful', 'website ']

Python | Removing newline character from string?

Method #1 : Using loop


userinput = ['paka\nf', 'o\ns', 'g\nreat', 'fo\nr', 'tutorials\n']


print("The original list : " + str(userinput))

res = []
for sub in userinput:
	res.append(sub.replace("\n", ""))
		
print("List after newline character removal : " + str(res))

I hope you get an idea about python remove newline.

I would like to have feedback on my infinityknow.com.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment