Remove all newlines from inside a string
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())
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.