Issue
When a string is being compared to an integer are the string and int compared with the ASCII code internally, or how is it? I know that strings compare greater than integers, but how does that internal comparison takes place?
>>> "a" > 1
True
Solution
In your example, 1 < "a"
because "i" for int
comes alphabetically before "s" for string
.
From the docs:
Objects of different types, except different numeric types and different string types, never compare equal; such objects are ordered consistently but arbitrarily (so that sorting a heterogeneous array yields a consistent result).
I believe this was one of the things changed in python 3 (you would get a TypeError
here).
As for how it is done in CPython, objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address. Note that this is part of the implementation, not a part of the language.
Answered By - wim
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.