Python 如何比较字符串和整数?

How can Python compare strings with integers?

给定以下代码:

a = '1'
if a == 1:
    print 'yes'
else:
    print 'no'

我们得到的输出为 no

Python 如何将字符串值与此处的 int 进行比较 (if a == 1)?在 C 中,这样的比较会出错,因为这是在比较不同的类型。

Python 不是 C。与 C 不同,Python 支持任意类型之间的相等性测试。

这里没有'how',字符串不支持对整数的相等性测试,整数不支持对字符串的相等性测试。所以 Python 回退到默认身份测试行为,但是对象 不是同一个对象 ,所以结果是 False.

参见参考文档的Value comparisons section

The default behavior for equality comparison (== and !=) is based on the identity of the objects. Hence, equality comparison of instances with the same identity results in equality, and equality comparison of instances with different identities results in inequality. A motivation for this default behavior is the desire that all objects should be reflexive (i.e. x is y implies x == y).

如果您想将整数与包含数字的字符串进行比较,则需要将字符串转换为整数或将整数转换为字符串,然后进行比较。