# enter code here
text=input()
word=input()
def search(text ,word):
if (text.find(word)):
print('Word found')
else:
print('Word not found')
search(text, word)
find
方法返回查找单词的索引,否则返回-1。
表示如果没有找到单词,text.find(word)
将返回-1,-1为真值。因此if语句的条件总是为真,因此总是输出word found
。
所以,一个正确的方法是这样做;
# enter code here
text=input()
word=input()
def search(text ,word):
if (text.find(word) != -1): # only change here
print('Word found')
else:
print('Word not found')
search(text, word)
text=input()
word=input()
def search(text ,word):
if (text in word):
print('Word found')
else:
print('Word not found')
search(text, word)
str.find(word)
如果子字符串存在于字符串中,则返回该子字符串第一次出现的索引。
如果子字符串不存在,则返回-1。
if (text.find(word)):
print('Word found')
else:
print('Word not found')
input text='hii'
word='hii'
output='Word not found'
find将返回第一个索引0,因此condition将为假,else块将执行