comparing strings and integers

Slawomir Nowaczyk slawek at cs.lth.se
Wed May 19 17:59:33 EDT 2004


On 19 May 2004 14:26:59 -0700
beliavsky at aol.com wrote:

#> By mistake I coded something like

#> print ("1" > 1)

#> and got the result "True". Comparing an integer and a string seems
#> meaningless to me, and I would prefer to have an exception thrown.
#> Can someone explain why Python allows comparisons between integers
#> and strings, and how it handles those cases? Why is "1" > 1?

From the Python Reference Manual, chapter 5.9 Comparisons:

"""

The operators <, >, ==, >=, <=, and != compare the values of two
objects. The objects need not have the same type. If both are numbers,
they are converted to a common type. Otherwise, objects of different
types always compare unequal, and are ordered consistently but
arbitrarily.

(This unusual definition of comparison was used to simplify the
definition of operations like sorting and the in and not in operators.
In the future, the comparison rules for objects of different types are
likely to change.)

"""

#> Pychecker does not warn about the line of code above -- I wish it
#> did.

Good point - it probably would be nice if it did. I don't know if it
is possible to check for such things in the general case, though.

-- 
 Best wishes,
   Slawomir Nowaczyk
     ( Slawomir.Nowaczyk at cs.lth.se )

Never argue with an idiot: first he will drag you down to his level,
then he will beat you with experience.





More information about the Python-list mailing list