gondu riya gondu riya -4 years ago 81
Python Question

how to avoid space on newline while joining a list

newContents = ['The', 'crazy', 'panda', 'walked', 'to', 'the', 'Maulik', 'and', 'then', 'picked.', 'A', 'nearby', 'Ankur', 'was\n', 'unaffected', 'by', 'these', 'events.\n']
print(' '.join(newContents))


output:

The crazy panda walked to the Maulik and then picked. A nearby Ankur was
unaffected by these events.


there is space before the (first) word unaffected on second line I don't want a space there.

Answer Source

There's a simple enough solution: replace \n[space] with \n. That way all spaces are left alone and only string replaced is \n[space] with newline without space

>>> newContents = ['The', 'crazy', 'panda', 'walked', 'to', 'the', 'Maulik', 'and', 'then', 'picked.', 'A', 'nearby', 'Ankur', 'was\n', 'unaffected', 'by', 'these', 'events.\n']
>>> print(' '.join(newContents).replace('\n ', '\n'))
The crazy panda walked to the Maulik and then picked. A nearby Ankur was
unaffected by these events.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download