sanyesh sanyesh - 1 month ago 17
Python Question

comparing string with int in python

Given the following code:

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


we get output as
no
.

How is Python comparing a string value to an int here (if a == 1)? In C such a comparison would give an error because this is comparing different types.

Answer

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 implies x == 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.