如何找到python另一个句子中的句子

如何找到python另一个句子中的句子,python,python-3.x,string,Python,Python 3.x,String,我构建了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 smil

我构建了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!")
它应该打印为“否!”,因为它有完全不同的句子。但是,它会打印“是”

这是因为绳子吗

我的代码或代码中是否有任何错误


我误解了什么吗?

您没有正确使用
,您应该-

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

您的问题是
是布尔运算符。它不对字符串进行操作,而是对字符串中的
字符串之类的表达式进行操作。试着这样做:

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):

看看这个例子:

if "some string":
  print("YES")
else:
  print("NO")
如果在您的环境中运行此命令,if子句的计算结果将始终为
True
,并显示“YES”输出

为什么??因为字符串没有与任何东西进行比较,因此可以将从不作为
False
语句进行计算

现在让我们看一下代码中的IF子句(具有较小的格式更改):

使用逻辑
运算符时,如果满足其中一个或两个条件,则if子句的计算结果为
True

text1不会与任何内容进行比较,并自动返回
True
,程序将输入if子句并执行print语句

相反,我们可以按如下方式重新编写代码:

if (text1 in sentence) or (text2 in sentence):

我们评估text1或text2是否是句子的子串

你的比较陈述有点错误。你基本上是这样说的:

if string or other_string in comp_string:
条件“if string”的第一部分的计算结果始终为true。您没有检查要比较的字符串中是否存在该字符串,这就是为什么您总是打印“是”的原因

你需要更加明确。您要做的是:

if string in comp_string or other_string in comp_string:

这应该正确计算。

它将
前面的第一句话计算为True,并返回。可能重复的
if string in comp_string or other_string in comp_string: