How can Python compare strings with integers?

Question:

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.

Asked By: sans0909

||

Answers:

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.

Answered By: Martijn Pieters
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.