如何在python 2.7中的列表( WordList
(中找到字符串( PartialWord
(?
PartialWord = "ab"
WordList = ['absail', 'rehab', 'dolphin']
使用通配符的搜索,例如:ab*
如果它以这些字母开头,它只会找到这个词(即,尽管两者都有" AB",结果只能给出腹部,但不得康复(。
单词列表将是一个字典,超过700kb。
您可以将str.startswith(..)
与 list classension 一起使用以下单词的列表,以:
>>> PartialWord = "ab"
>>> WordList = ['absail', 'rehab', 'dolphin']
>>> [word for word in WordList if word.startswith(PartialWord)]
['absail']
根据str.startswith
文档:
str.startswith(前缀[,start [,end]](:
如果字符串启动,返回
True
使用前缀,否则返回False
。前缀也可以是tuple
要寻找的前缀。使用可选的 start ,测试字符串开始于 那个位置。使用可选的 end ,停止比较该字符串 位置。
for word in WordList:
if word.startswith(PartialWord):
print word
正如前面所述的每个人, str.startswith
是您的功能。您可以研究更复杂操作的正则方式。REGEX
您可以做:
>>> WL = ['absail', 'rehab', 'dolphin']
>>> PW="ab"
>>> L=[a for a in WL if a[:len(PW)]==PW]
>>> L
['absail']