我正在使用Python v2,我想知道你是否能知道一个词是否在一个字符串中。
我找到了一些关于识别单词是否在字符串中的信息--使用.find,但是否有办法做一个IF语句。我希望能有类似以下的东西。
if string.find(word):
print 'success'
谢谢你的帮助。
if 'seek' in 'those who seek shall find':
print('Success!')
但请记住,这匹配的是一连串的字符,而不一定是整个单词--例如,'word'中的'swordsmith'`是True。如果你只想匹配整个单词,你应该使用正则表达式。
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
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.'