How can Python compare strings with integers?
Python is not C. Unlike C, Python supports equality testing between arbitrary types.
There is no 'how' here, strings don't support equality testing to integers, integers don't support equality testing to strings. So Python falls back to the default identity test behaviour, but the objects are not the same object, so the result is False
.
See the Value comparisons section of the reference documentation:
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
impliesx == y
).
If you wanted to compare integers to strings containing digits, then you need to convert the string to an integer or the integer so a string, then compare.