如果需要在句子字符串中查找整个单词,以下简单代码可以工作。任何人都可以批评它,或找到可能失败的边界条件吗?
a = input("Enter a sentence:")
w = input ("Enter a word to be found in the sentence")
if w.lower() in a.lower():
print("It is present")
else:
print("It is not present")
答案 0 :(得分:4)
根据@Amadan 的评论,
<块引用>这更多地取决于对问题的解释。 “我喜欢你的围巾”这句话中出现了“汽车”这个词吗?有些人会说是的——“围巾”里面有“车”——对于这些人来说,你的代码可以正常工作。
为此,您的代码运行良好。
a = input("Enter a sentence:")
w = input ("Enter a word to be found in the sentence:")
if w.lower() in a.lower():
print("It is present")
else:
print("It is not present")
输出:
Enter a sentence:I like your scarf
Enter a word to be found in the sentence:car
It is present
>>>
<块引用>
有些人会说不——“汽车”在这句话中不是一个词——他们会判断你的代码不正确。
为此,请使用:
a = input("Enter a sentence:")
w = input ("Enter a word to be found in the sentence:")
if w.lower() in a.lower().split():
print("It is present")
else:
print("It is not present")
输出:
Enter a sentence:I like your scarf
Enter a word to be found in the sentence:car
It is not present
答案 1 :(得分:0)
这完美地工作。由于 input()
将所有内容都视为字符串,因此您甚至可以检查特殊字符或带有重音字母的单词。