Skip to main content
 首页 » 编程设计

python之如何从列表中的字符串末尾去除特定标点符号并使所有单词小写

2025年05月04日29jillzhang

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

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

我只需要从每个字符串的末尾删除所有包含 '"-,.:;!? 的标点符号,并将所有单词设为小写。

Io 我需要 'Twas' 变成 'twas' 我需要 'wabe:' 变成 'wabe' 等...列表中我未包含在此处的其他单词在末尾包含其他标点符号。

我尝试使用 .rstrip() 和 .lower() 大小写,但我不知道如何使用 for 或 while 循环遍历列出并执行此操作。如果有另一种不需要使用 .rstrip 或 .lower 的方法,我愿意接受。

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

请您参考如下方法:

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

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