I currently have a list, one index of which contains a double newline (\n\n
). I want to remove the \n\n
and concatenate the two strings it separated.
I.e. "hello\n\nworld"
becomes "hello world"
, and not "hello", "world"
.
Asked
Active
Viewed 1,987 times
-1

innisfree
- 2,044
- 1
- 14
- 24

morgan_creamin
- 9
- 2
-
Possible duplicate of [Python - Join with newline](https://stackoverflow.com/questions/14560863/python-join-with-newline) – Panagiotis Drakatos May 03 '18 at 23:42
4 Answers
0
How about
x = [" hello \n\n", "world"]
r = " ".join(w.strip() for w in x)
# 'hello world'
Note that this removed leading and trailing white space and newlines. If you want to retain leading and trailing white spaces and remove only trailing "\n"
, you may prefer
x = [" hello \n\n", "world"]
r = " ".join(w.rstrip("\n") for w in x)
# ' hello world'

innisfree
- 2,044
- 1
- 14
- 24
-
If OP wanted to retain other leading or trailing whitespace then `' '.join(w.rstrip('\n') for w in x)` might be better. – mhawke May 03 '18 at 23:41
0
You stated that you want to remove the sequence of double new lines in the input, which I assume means leaving other whitespace untouched:
>>> l = ['hello\n\n', 'world']
>>> result = ' '.join(l).replace('\n\n', '')
>>> result
'hello world'
This will not perturb any single new lines or other whitespace that might be present in the values of the list, e.g.
>>> l = [' hello\n\n', ' there \n ', 'world']
>>> ' '.join(l).replace('\n\n', '')
' hello there \n world'

mhawke
- 84,695
- 9
- 117
- 138
0
a_list = ["hello\n\n", "world"]
new_list = []
for item in a_list:
new_list.append(
item.replace('\n\n', '')
)
' '.join(new_list)

Joseph Mancuso
- 403
- 5
- 11
-
This won't work. You need to update the values in the list before applying `join()`, but the list is not updated in the for loop. – mhawke May 03 '18 at 23:52
-
True, just updated. I could have sworn I changed my answer after I posted that lol – Joseph Mancuso May 04 '18 at 16:19
0
Use something like
mystr = mystr.replace("\n\n"," ").
Then replace old string in list with new joined string.

Dzliera
- 646
- 5
- 15