为什么if语句成功?

jlE*_*lEe 3 python

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

    s="( )"
    if ("if" and ":" and " ") in s:
        print(s)
Run Code Online (Sandbox Code Playgroud)

For*_*Bru 10

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

>>> "if" and ":" and " "
' '
>>> _ in "( )"
True
>>> ' ' in "( )"
True
>>> ("if" and ":" and " ") == ' '
True
Run Code Online (Sandbox Code Playgroud)

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!
Run Code Online (Sandbox Code Playgroud)

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