如何在 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(prefix[, start[, end]]):
Return
Trueif string starts with the prefix, otherwise returnFalse. prefix can also be atupleof prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position.
