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.
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.
rstrip('\n') . This will strip all newlines from the end of the string, not just one.
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.
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
As mentioned by @john, the most robust answer is:
string = "a\nb\rv" new_string = " ".join(string.splitlines())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With