【发布时间】:2021-04-19 08:14:44
【问题描述】:
问题是,OR 不适用于 python 3 中的 IF 条件,如果我编写多个 IF 条件,那么它可以正常工作,如下所示:
s1 has 3 matches in text[i]
s2 has 1 matches in text[i]
text[i] is read line by line and contain s1 OR s1
不工作:
c=0
if s1 in text[i] or s2 in text[i]:
c = c + 1
输出:
3 # here correct total 4 condition, s1 true as 3 and s2 true as 1 !
工作:
c=0
if s1 in text[i] :
c = c + 1
if s2 in text[i] :
c = c + 1
期望/正确结果为 4
如何将两个条件写在一行中?
【问题讨论】:
-
第一个代码将
c保留为 0 或 1。第二个代码将c保留为 0、1 或 2。它们都没有将其设置为 4。它们都没有输出任何内容。跨度> -
@khelwood 我更新了问题,如果有任何疑问,请告诉我
-
您似乎正在寻找多个匹配项。您不能为此使用
in,因为in停止查看第一场比赛。查找字符串方法count()并改用它。 -
也许您想发布一个 minimal reproducible example 来实际展示您所描述的行为。
-
考虑如果
s1和s2都在text[i]中会发生什么。
标签: python python-3.x if-statement syntax