python 中有两个布尔值的运算符

Operator with two Boolean in python

为什么运算符“&”在这两个表达式中不起作用?

# First, type bool
bool(re.search(r'\d', "4foo"))
>True
# Second, type bool
len("4foo")==4
>True
type(len("4foo")==4)))
>bool

像这样将两者与运算符“&”一起使用时,我得到 False 这是不正确的:

# Expected output as this example:
True&True
>True

# The "wrong" output:
 bool(re.search(r'\d', "4foo"))& (len("4foo")==4)
>False

疯狂了一个小时后,我 "solved" 通过使用我从未想过会成为 "problem":

# The "correct" output(transforming a bool type into a bool type something that works but seems stupid...):
 bool(re.search(r'\d', "4foo"))&bool(len("4foo")==4)
>True

解决方案

bool(re.search(r'\d', "4foo")) and len("4foo")==4

您需要这样做:

&替换为and:

In [638]: bool(re.search(r'\d', "4foo")) and len("4foo")==4                                                                                                                                                 
Out[638]: True

and 测试两个表达式在逻辑上是否为真,而 &(当与 True/False 值一起使用时)测试两个表达式是否为真。

注意括号

len("4foo"==4) ------------> len("4foo")==4

和条件

re.search(r'\d', "4foo")and len("4foo")==4