2024-09-27 00:13:40 发布
网友
在Python2.7中,如何在列表(WordList)中找到字符串(PartialWord)?在
WordList
PartialWord
PartialWord = "ab" WordList = ['absail', 'rehab', 'dolphin']
使用通配符搜索:ab*
如果它只会找到这个单词,如果它以这些字母开头(也就是说,结果应该只给出absail,而不是rehab,尽管两者都有“ab”)。在
单词表将是一个超过700KB的字典。在
for word in WordList: if word.startswith(PartialWord): print word
正如前面提到的,str.startswith是您的函数。您可以研究更复杂操作的正则表达式模式。regex
str.startswith
您可以使用^{}和列表理解来获得以某个字符串开头的单词列表,如下所示:
>>> 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.
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.
True
False
tuple
正如前面提到的,
str.startswith
是您的函数。您可以研究更复杂操作的正则表达式模式。regex您可以使用^{} 和列表理解来获得以某个字符串开头的单词列表,如下所示:
根据^{} document :
相关问题 更多 >
编程相关推荐