我正在使用Python,我试图找出你是否可以判断一个单词是否在字符串中。
我找到了一些关于识别单词是否在字符串中的信息-使用.find,但是否有一种方法来执行if语句。我想要这样的东西:
if string.find(word):
print("success")
我正在使用Python,我试图找出你是否可以判断一个单词是否在字符串中。
我找到了一些关于识别单词是否在字符串中的信息-使用.find,但是否有一种方法来执行if语句。我想要这样的东西:
if string.find(word):
print("success")
当前回答
你可以在"word"前后加一个空格。
x = raw_input("Type your word: ")
if " word " in x:
print("Yes")
elif " word " not in x:
print("Nope")
这样它会查找“word”前后的空格。
>>> Type your word: Swordsmith
>>> Nope
>>> Type your word: word
>>> Yes
其他回答
出了什么问题:
if word in mystring:
print('success')
我相信这个答案更接近最初的问题:在字符串中查找子字符串,但只有在整个单词?
它使用了一个简单的正则表达式:
import re
if re.search(r"\b" + re.escape(word) + r"\b", string):
print('success')
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.')
您可以将字符串拆分为单词并检查结果列表。
if word in string.split():
print("success")
if 'seek' in 'those who seek shall find':
print('Success!')
但请记住,这匹配的是一个字符序列,而不一定是一个完整的单词——例如,'swordsmith'中的'word'是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