Skip to main content
 首页 » 编程设计

python之在列表中找到一段字符串并替换

2025年05月04日12落叶

我遇到过一些演示如何在列表中查找字符串并替换的帖子,但我很难将搜索推广到仅一段字符串。

例如

listX = ['color green', 'shape circle', 'above t'] 

我想找到所有以 'above' 开头的字符串,我已经能够使用 any 对列表进行一些最小的搜索并留下以下空格 'above ' 但我不知道如何替换我找到的内容。

我尝试创建的输出是:

['color green', 'shape circle', 'above'] 

我还想弄清楚如何从列表中一起删除以“above”开头的字符串。

请您参考如下方法:

['above' if x.startswith('above') else x for x in listX] 

如果你想删除所有以 'above' 开头的字符串,那么你可以像@JonClements 在评论中提到的那样做:

[x for x in listX if not x.startswith('above')] 

或者:

from itertools import filterfalse 
list(filterfalse(lambda x: x.startswith('above'), listX))