有人可以解释一下为什么将字符串和布尔值连接起来(使用'in'关键字)会返回False值,而不是类型错误吗?
>>> var1 = "fish"
>>> var2 = "fi"
>>> print("True that " + var1 in var2) # str + bool returns False not TypeError
**False**
>>> print("True that ", var1 in var2) # str, bool works with comma method
True that False
>>> print("True that " + var2 in var1) # str + bool returns False not TypeError
**False**
>>> print("True that ",var2 in var1) # stre , bool works with comma method
True that True
>>> print(var2 in var1)
True
>>> type("True that ")
<class 'str'>
>>> type(var2 in var1)
<class 'bool'>
答案 0 :(得分:4)
+
运算符的优先级高于in
运算符,因此:
"True that " + var1 in var2
有效
("True that " + var1) in var2
因此返回False
,其中var1
是'fish'
,而var2
是'fi'
。
如果您想让var1 in var2
运算符提高+
,则必须在括号中加上TypeError
:
"True that " + (var1 in var2)
答案 1 :(得分:2)
您的优先级有误。 a + b in c
被解析为(a + b) in c
,而不是a + (b in c)
。没有发生字符串+布尔连接。