-3

I thought when comparing a int to a string (with a numeric value) in python, it is not necessary to explicitly convert the string. But the following code taught me a lesson:

size = raw_input("a numeric value:")
a_str = 'abcdefghijklmn'
if len(a_str) > size:
    print("The string is longer.")
elif len(a_str) < size:
    print("The string is shorter.")
else:
    print("they are equal in length.")

No matter what value I typed in, it always chose len(a_str) < size until I convert the size using int(size).

ashastral
  • 2,818
  • 1
  • 21
  • 32

1 Answers1

2

python manual clearly mentioned that

CPython implementation detail: 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.

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). Furthermore, some types (for example, file objects) support only a degenerate notion of comparison where any two objects of that type are unequal. Again, such objects are ordered arbitrarily but consistently. The <, <=, > and >= operators will raise a TypeError exception when any operand is a complex number.

Related question:

How does Python compare string and int?

Community
  • 1
  • 1
Surya
  • 4,824
  • 6
  • 38
  • 63