Skip to main content
 首页 » 编程设计

python之过滤以特定关键字开头的字符串列表

2025年05月04日26java哥

如何在 Python 2.7 中的列表 (WordList) 中找到字符串 (PartialWord)?

PartialWord = "ab" 
WordList = ['absail', 'rehab', 'dolphin'] 

使用通配符进行搜索,如:ab*

它只能找到以这些字母开头的单词(即结果应该只给出 absail,而不是 rehab,尽管两者都有“ab”)。

WordList 将是一个字典,超过 700KB。

请您参考如下方法:

您可以使用 str.startswith(..)连同列表理解 以获取以某个字符串开头的单词列表:

>>> PartialWord = "ab" 
>>> WordList = ['absail', 'rehab', 'dolphin'] 
 
>>> [word for word in WordList if word.startswith(PartialWord)] 
['absail'] 

根据 str.startswith document :

str.startswith(prefix[, start[, end]]):

Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position.