Possible Duplicate:
How does Python compare string and int?
I had a Python script that wasn’t evaluating two values as expected. The value '10' was determined as being greater than 200. The issue was the variable holding the value of ’10’ was actually a string and not an integer (whereas 200 was an integer).
My question is:
What is the process Python goes through when evaluating a string against an integer? How does it make the comparison?
For example:
string="10"
int=200
if string >= int:
print("String is greater")
else:
print("Int is greater")
Would output:
String is greater
Why is this? I would have thought Python would just exit with an error when trying to compare the two types.
Python 2.x allows comparing objects of any type, and guarantees that results are reprroducible. In Python 3.x, comparing objects that cannot be ordered meaningfully results in an error. The rationale for the 2.x behaviour was that it is sometimes convenient to be able to
list.sort()heterogeneous lists. The rationale for the new 3.x behaviour is that the old behaviour hid errors.The ordering used by Python 2.x is an implementation detail. CPython uses some rather strange rules, roughly
(No guarantees that I got this right, but I won’t bother to check. It’s an implemetation detail, don’t rely on it.)