与“ in”关键字串联会产生错误的结果

时间:2019-02-23 00:52:46

标签: python string boolean concatenation

有人可以解释一下为什么将字符串和布尔值连接起来(使用'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'>

python code using concatenation with bool

2 个答案:

答案 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)。没有发生字符串+布尔连接。