1

我有一个字符串列表,需要从列表中每个字符串的末尾删除某些标点符号。清单如下:

list = ['Twas', 'brillig,', 'and', 'the', 'slithy', 'toves', 'Did', 'gyre',
        'and', 'gimble', 'in', 'the', 'wabe:']  #the list is a lot longer

我需要'"-,.:;!?从每个字符串的末尾去掉所有标点符号,并使所有单词小写。

Io I need 'Twas'to become 'twas'and I need 'wabe:'to become'wabe'等...列表中我未在此处包含的其他单词在末尾包含其他标点符号。

我尝试使用.rstrip().lower()case,但我不知道如何使用 for 或 while 循环遍历列表中的每个字符串并执行此操作。如果有其他方式不需要使用.rstrip或者.lower我对他们开放。

我是使用python的初学者,所以非常基本的答案会对我有所帮助,如果您能准确解释您的工作,将不胜感激。

4

1 回答 1

8
>>> [el.lower().rstrip('\'\"-,.:;!?') for el in list]
['twas', 'brillig', 'and', 'the', 'slithy', 'toves', 'did', 'gyre', 'and', 'gimble', 'in', 'the', 'wabe']

这是一个列表推导式,它是一种编写生成列表的 for 循环的单行方式。它逐项遍历列表,将每个元素设置为小写,然后去除尾随字符 '"-,.:;!?

于 2012-04-09T10:30:22.443 回答