给定单词作为输入,在文本中没有找到,但它仍然返回word found作为输出,而不是word not found.你能纠

  • 本文关键字:found word 输出 返回 not 单词作 文本 python
  • 更新时间 :
  • 英文 :

# 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块将执行

最新更新