comparing strings and integers
Gary Herron
gherron at islandtraining.com
Wed May 19 17:57:54 EDT 2004
On Wednesday 19 May 2004 02:26 pm, 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?
>
> Pychecker does not warn about the line of code above -- I wish it did.
>
> In my code what I really intended was to convert the "1" to an int and
> THEN do a comparison.
>From the manual:
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.)
More information about the Python-list
mailing list