4 回答
TA贡献1998条经验 获得超6个赞
if 'seek' in 'those who seek shall find':
print('Success!')
但请记住,这匹配一系列字符,不一定是整个单词 - 例如,'word' in 'swordsmith'是真的。如果你只想匹配整个单词,你应该使用正则表达式:
import re
def findWholeWord(w):
return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search
findWholeWord('seek')('those who seek shall find') # -> <match object>
findWholeWord('word')('swordsmith') # -> None
TA贡献1828条经验 获得超13个赞
如果您想知道整个单词是否在以空格分隔的单词列表中,只需使用:
def contains_word(s, w):
return (' ' + w + ' ') in (' ' + s + ' ')
contains_word('the quick brown fox', 'brown') # True
contains_word('the quick brown fox', 'row') # False
这种优雅的方法也是最快的。与Hugh Bothwell和daSong的方法相比:
>python -m timeit -s "def contains_word(s, w): return (' ' + w + ' ') in (' ' + s + ' ')" "contains_word('the quick brown fox', 'brown')"
1000000 loops, best of 3: 0.351 usec per loop
>python -m timeit -s "import re" -s "def contains_word(s, w): return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search(s)" "contains_word('the quick brown fox', 'brown')"
100000 loops, best of 3: 2.38 usec per loop
>python -m timeit -s "def contains_word(s, w): return s.startswith(w + ' ') or s.endswith(' ' + w) or s.find(' ' + w + ' ') != -1" "contains_word('the quick brown fox', 'brown')"
1000000 loops, best of 3: 1.13 usec per loop
编辑: Python 3.6+的这个想法略有变化,同样快:
def contains_word(s, w):
return f' {w} ' in f' {s} '
TA贡献1845条经验 获得超8个赞
find返回一个整数,表示搜索项找到的位置的索引。如果未找到,则返回-1。
haystack = 'asdf'
haystack.find('a') # result: 0
haystack.find('s') # result: 1
haystack.find('g') # result: -1
if haystack.find(needle) >= 0:
print 'Needle found.'
else:
print 'Needle not found.'
添加回答
举报