从单词列表中删除/ n - python

时间:2010-08-29 11:00:13

标签: python list string

我有一个列表如下

<'Jellicle','Cats','are','black','和','white,\ nJellicle','Cats','are','而','small; \ nJellicle', '猫','是','快乐','和','明亮,'和','愉快','到','听','什么时候','他们','caterwaul。\ nJellicle', '猫','有','开朗','面孔,\ nJellicle','猫','有','明亮','黑','眼睛; \ n他们','喜欢','到', “练习”,“他们的”,“空气”,“和”,“优雅”,“等待”,“等待”,“'”,“月亮”,“上升”,“崛起”。 N']

如何删除/ n所以我最终得到一个列表,其中每个单词都是单独的,没有/ n。

Grammer被允许留在列表中。

感谢

3 个答案:

答案 0 :(得分:2)

最简单的(虽然不是最佳表现)可能是加入然后分裂:

l = ('\n'.join(l)).split('\n')

实际上,您似乎是通过拆分空间来创建此列表。如果是这样,您可能想要首先重新考虑如何创建此列表以避免这一额外步骤。您可以通过使用不带任何参数的s.split()拆分匹配空格的正则表达式直接拆分到正确的结果,或者更好。

答案 1 :(得分:1)

>>> [i for el in lst for i in el.splitlines()]
['Jellicle', 'Cats', 'are', 'black', 'and', 'white,', 'Jellicle', 'Cats', 'are', 'rather', 'small;', 'Jellicle', 'Cats', 'are', 'merry', 'and', 'bright,', 'And', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.', 'Jellicle', 'Cats', 'have', 'cheerful', 'faces,', 'Jellicle', 'Cats', 'have', 'bright', 'black', 'eyes;', 'They', 'like', 'to', 'practise', 'their', 'airs', 'and', 'graces', 'And', 'wait', 'for', 'the', 'Jellicle', 'Moon', 'to', 'rise.']

答案 2 :(得分:0)

>>> l = ['Jellicle', 'Cats', 'are', 'black', 'and', 'white,\nJellicle', 'Cats', 'are', 'rather', 'small;\nJellicle', 'Cats', 'are', 'merry', 'and', 'bright,\nAnd', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.\nJellicle', 'Cats', 'have', 'cheerful', 'faces,\nJellicle', 'Cats', 'have', 'bright', 'black', 'eyes;\nThey', 'like', 'to', 'practise', 'their', 'airs', 'and', 'graces\nAnd', 'wait', 'for', 'the', 'Jellicle', 'Moon', 'to', 'rise.\n']
>>> [i.strip(',;') for v in l for i in v.split()]
相关问题