开发者

removing /n from list of words - python

I have a list as below

['Jellicle', 'Cats', 'are', 'black', 'and', 'white,\nJellicle', 'Cats', 'are', 'rather', 'small;\nJellicle', 'Cats', 'are', 'merry', 'an开发者_JS百科d', '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']

How can I remove the /n so I end up with a list with each word as a seperate thing with no /n.

Grammer is allowed to be left in the list.

thanks


The simplest (although not the best performing) is probably to join then split:

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

In fact it looks like you created this list by splitting on space. If so, you might want to reconsider how to create this list in the first place to avoid this extra step. You can split directly to the correct result by splitting on a regular expression matching whitespace, or better, by using s.split() without any arguments.


>>> [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.']


>>> 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()]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜