我有一个字符串列表,需要从列表中每个字符串的末尾剥离一些标点符号。该列表如下:
list = ['Twas', 'brillig,', 'and', 'the', 'slithy', 'toves', 'Did', 'gyre',
'and', 'gimble', 'in', 'the', 'wabe:'] #the list is a lot longer
我需要从每个字符串的末尾删除包含'"-,.:;!?
的所有标点符号,并将所有单词设为小写。
我需要'Twas'
成为'twas'
,我需要'wabe:'
才能成为'wabe'
等等...列表中我未包含的其他字词包含最后的另一个标点符号。
我尝试使用.rstrip()
和.lower()
大小写,但我不知道如何使用for或while循环遍历列表中的每个字符串并执行此操作。如果有其他方式不需要使用.rstrip
或.lower
,我会向他们开放。
我是使用python的初学者,所以非常基本的答案对我有帮助,如果你能准确地解释你做了什么,我将不胜感激。
答案 0 :(得分:8)
>>> [el.lower().rstrip('\'\"-,.:;!?') for el in list]
['twas', 'brillig', 'and', 'the', 'slithy', 'toves', 'did', 'gyre', 'and', 'gimble', 'in', 'the', 'wabe']
这是一个列表理解,它是编写一个产生列表的for循环的单行方式。它逐项遍历列表,将每个元素设置为小写,然后剥离尾随字符“ - ,。:;!?