Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all newlines from inside a string

I'm trying to remove all newline characters from a string. I've read up on how to do it, but it seems that I for some reason am unable to do so. Here is step by step what I am doing:

string1 = "Hello \n World" string2 = string1.strip('\n') print string2 

And I'm still seeing the newline character in the output. I've tried with rstrip as well, but I'm still seeing the newline. Could anyone shed some light on why I'm doing this wrong? Thanks.

like image 919
LandonWO Avatar asked Nov 08 '12 22:11

LandonWO


People also ask

How do you remove line breaks from a string?

Use the String. replace() method to remove all line breaks from a string, e.g. str. replace(/[\r\n]/gm, ''); . The replace() method will remove all line breaks from the string by replacing them with an empty string.

Does Rstrip remove newline?

rstrip('\n') . This will strip all newlines from the end of the string, not just one.

How do you remove newlines and spaces from a string in Python?

strip() Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.


2 Answers

strip only removes characters from the beginning and end of a string. You want to use replace:

str2 = str.replace("\n", "") re.sub('\s{2,}', ' ', str) # To remove more than one space  
like image 162
mipadi Avatar answered Sep 25 '22 11:09

mipadi


As mentioned by @john, the most robust answer is:

string = "a\nb\rv" new_string = " ".join(string.splitlines()) 
like image 43
Chris Sewell Avatar answered Sep 25 '22 11:09

Chris Sewell