3

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
wim
  • 302,178
  • 90
  • 548
  • 690
Rajeev
  • 42,191
  • 76
  • 179
  • 280
  • 4
    Possible duplication? http://stackoverflow.com/questions/9306285/how-does-python-compare-strings-and-integers – CppLearner Feb 20 '12 at 06:30

2 Answers2

9

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.

wim
  • 302,178
  • 90
  • 548
  • 690
-2

You should check the source of the __gt__ method of the inbuilt string object to know the details but my guess is that the 1 is converted to a string using the str function and then then the two are compared.

Noufal Ibrahim
  • 69,212
  • 12
  • 131
  • 165