Remove all newlines from inside a string

169,861

Solution 1

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 

Solution 2

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

string = "a\nb\rv"
new_string = " ".join(string.splitlines())

Solution 3

Answering late since I recently had the same question when reading text from file; tried several options such as:

with open('verdict.txt') as f: 

First option below produces a list called alist, with '\n' stripped, then joins back into full text (optional if you wish to have only one text):

alist = f.read().splitlines()
jalist = " ".join(alist)

Second option below is much easier and simple produces string of text called atext replacing '\n' with space;

atext = f.read().replace('\n',' ')

It works; I have done it. This is clean, easier, and efficient.

Solution 4

strip() returns the string after removing leading and trailing whitespace. see doc

In your case, you may want to try replace():

string2 = string1.replace('\n', '')

Solution 5

or you can try this:

string1 = 'Hello \n World'
tmp = string1.split()
string2 = ' '.join(tmp)
Share:
169,861
LandonWO
Author by

LandonWO

Updated on March 17, 2021

Comments

  • LandonWO
    LandonWO about 3 years

    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.