这是我目前的代码
sentence= input("Enter a sentence")
keyword= input("Input a keyword from the sentence")
keyword.upper() == keyword.lower()
words = sentence.split(' ')
for (i, subword) in enumerate(words)
if (subword == keyword)
print(i+1)
if (keyword not in sentence)
print("Sorry, that word wasnt found in the sentence")
以下不起作用
keyword.upper() == keyword.lower()
我可以将哪些内容添加到我的代码中?
答案 0 :(得分:2)
您通常会使用in
关键字检查子字符串是否属于另一个字符串:
sentence = input("Sentence: ")
keyword = input("Keyword: ")
if keyword in sentence:
print("Found it!")
else:
print("It's not there...")
要变为不区分大小写,您必须将句子的小写版本与关键字的小写版本(或两者都大写,没有区别)进行比较:
if keyword.lower() in sentence.lower():
# ...
答案 1 :(得分:0)
我可以看到你在尝试将upper()和lower()设置为相同的值时的逻辑,但它并不像那样工作。
在比较子字和关键字时,您需要在两个字符串上调用.upper()或.lower(),这样它们将始终为小写或两者都为大写。
答案 2 :(得分:0)
您必须像这样更改代码:
sentence= input("Enter a sentence")
keyword = input("Input a keyword from the sentence").lower()
Found = False
words = sentence.split(' ')
for (i, subword) in enumerate(words)
if (subword.lower() == keyword)
print('keyword found at position', i+1)
Found = True
if not found:
print("Sorry, that word wasn't found in the sentence")