以特定关键字开头的字符串的筛选器列表

2024-09-27 00:13:40 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python2.7中,如何在列表(WordList)中找到字符串(PartialWord)?在

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

使用通配符搜索:ab*

如果它只会找到这个单词,如果它以这些字母开头(也就是说,结果应该只给出absail,而不是rehab,尽管两者都有“ab”)。在

单词表将是一个超过700KB的字典。在


Tags: 字符串列表字典ab字母单词wordlist通配符
3条回答
for word in WordList:
    if word.startswith(PartialWord):
        print word    

正如前面提到的,str.startswith是您的函数。您可以研究更复杂操作的正则表达式模式。regex

您可以使用^{}列表理解来获得以某个字符串开头的单词列表,如下所示:

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

>>> [word for word in WordList if word.startswith(PartialWord)]
['absail']

根据^{} 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.

相关问题 更多 >

    热门问题