-1

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".

innisfree
  • 2,044
  • 1
  • 14
  • 24

4 Answers4

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
0

Use something like
mystr = mystr.replace("\n\n"," "). Then replace old string in list with new joined string.

Dzliera
  • 646
  • 5
  • 15