这是我迄今为止的代码
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()
我可以在代码中添加什么?
您通常会使用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():
# ...
我可以看到你试图将upper()和lower()设置为相同值的逻辑,但它并不是这样工作的。
在比较子词和关键字时,需要对两者调用.opper()或.lower(),以便它们始终为小写或均为大写。
您必须这样更改代码:
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")