如何在加入列表时避免换行上的空格

时间:2017-02-27 12:58:26

标签: python

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

输出:

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

在第二行(第一)单词未受影响之前有空格我不想在那里有空格。

5 个答案:

答案 0 :(得分:3)

您可以在加入后将其删除:

your_string = ' '.join(newContents).replace('\n ', '\n')
print(your_string)

答案 1 :(得分:2)

这是一个足够简单的解决方案:将\n[space]替换为\n。这样,所有空格都保持不变,只更换字符串为\n[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.

答案 2 :(得分:1)

您可以使用replace检查换行后的空格:

print(' '.join(newContents).replace('\n ', '\n'))

输出:

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

答案 3 :(得分:1)

使用re.sub功能在换行符后立即删除空格:

import re

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

输出:

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

以上内容还将删除换行符后的多个空格(如果出现)

答案 4 :(得分:-1)

从每个空格中删除空格:

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