How can Python compare strings with integers?

前端 未结 1 1391
半阙折子戏
半阙折子戏 2020-12-04 02:26

Given the following code:

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

we get output as no.

How is Py

相关标签:
1条回答
  • 2020-12-04 03:10

    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.

    0 讨论(0)
提交回复
热议问题