为什么if语句成功?

时间:2019-05-14 17:10:48

标签: python

下面的if语句成功,并打印s的值。但是,如果删除:和/或空格条件,则它将失败。我很困惑为什么它首先会成功。

    s="( )"
    if ("if" and ":" and " ") in s:
        print(s)

3 个答案:

答案 0 :(得分:10)

括号中的内容是一个表达式,其计算结果为单个值:

>>> "if" and ":" and " "
' '
>>> _ in "( )"
True
>>> ' ' in "( )"
True
>>> ("if" and ":" and " ") == ' '
True

and就像普通的布尔AND,但在类固醇上:

>>> 0 and 0
0
>>> 0 and 1
0
>>> 1 and 0
0
>>> 1 and 1
1
>>> 0 and 'hello'
0
>>> 'hello' and 0
0
>>> 'hello' and 'hello'
'hello'  # WAIT. That's illegal!

因此,and返回真实对象(或第一个非真实对象)的中的 last 真实对象它遇到)。注意,它返回一个 object ,而不是严格的布尔值,就像二进制AND一样。

答案 1 :(得分:0)

看看如果您刚跑步会发生什么:

"if" and ":" and " "

您将获得:

" "

这是因为您首先要评估括号中的所有内容,然后检查其结果是否在s

要评估您要寻找的内容,您将需要以下内容:

if "if" in s and ":" in s and " " in s:
    print(s)

或者:

if all(["if" in s, ":" in s, " " in s]):
    print(s)

答案 2 :(得分:0)

a and b returns b if a is True, else returns a

因此,我们"if" and ":" and " "等效于("if" and ":") and " "

  • "if" and ":"":"
  • ":" and " "" "

因此,"if" and ":" and " "" " 。给定s="( )",结果" "s="( )"内部 这就是为什么打印print(s)

注意" "为真,而""为假