我构建了python代码,可以找到下面另一个句子中的句子,但效果不佳。
sentence = "While speaking to Ross, Rachel comes to terms with something that was bothering her."
if "Rachel has made coffee to Joey and Chandler for the first time of her entire life." or "Monica can't stop smiling while having a conversation with Rachel." in sentence:
print("YES")
else
print("NO!")
应打印"NO!"
,因为它的句子完全不同。但是,它会打印"YES"
。
这是因为字符串吗?
我在代码中做错了什么吗?
我误会了吗?
答案 0 :(得分:7)
您没有正确使用or
-
if "Rachel has made coffee to Joey and Chandler for the first time of her entire life." in sentence or "Monica can't stop smiling while having a conversation with Rachel." in sentence:
如果变量为None或空列表,空字符串或空集或空字典(...),则if条件返回False
,否则返回True
。
答案 1 :(得分:1)
您的问题是or
是布尔运算符。它不适用于字符串,但不能用于string in string
之类的表达式。尝试这样的事情:
if ("Rachel has made coffee to Joey and Chandler for the first time of her entire life." in sentence)or ("Monica can't stop smiling while having a conversation with Rachel." in sentence):
答案 2 :(得分:1)
看看这个例子:
if "some string":
print("YES")
else:
print("NO")
如果在您的环境中运行此命令,则if子句将始终计算为True
,并显示“ YES”的输出。
为什么?由于未将字符串与任何内容进行比较,因此从不不能将其评估为False
语句
现在,让我们看一下代码中的if子句(格式略有更改):
sentence = "While speaking to Ross, Rachel comes to terms with something that was
bothering her."
text1 = "Rachel has made coffee to Joey and Chandler for the first time of her entire life."
text2 = "Monica can't stop smiling while having a conversation with Rachel."
if (text1) or (text2 in sentence):
print("YES")
else:
print("NO")
使用逻辑or
运算符时,如果满足两个或两个条件,则if子句的值为True
。
text1不与任何内容进行比较,并自动返回True
,程序将输入if子句并执行您的print语句
相反,我们可以按以下方式重新编写代码:
if (text1 in sentence) or (text2 in sentence):
我们评估text1或text2是句子的子字符串。
答案 3 :(得分:0)
您的比较语句有点错误。您基本上是这样说的:
if string or other_string in comp_string:
条件“如果字符串”的第一部分始终为true。您无需检查要比较的字符串中是否存在该字符串,这就是为什么您始终打印“是”的原因。
您需要更加明确。您想做的是这样:
if string in comp_string or other_string in comp_string:
这应该正确评估。