The Python Oracle

Python string comparison with different case and float

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Dreaming in Puzzles

--

Chapters
00:00 Question
00:37 Accepted answer (Score 6)
02:07 Answer 2 (Score 8)
02:28 Thank you

--

Full question
https://stackoverflow.com/questions/1294...

Accepted answer links:
[ASCII table]: http://www.asciitable.com/
[Does Python have a built in function for string natural sort?]: https://stackoverflow.com/questions/4836...
[Comparison magic methods]: http://www.rafekettler.com/magicmethods....
[compared based on the name of their type]: https://stackoverflow.com/questions/3270...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ANSWER 1

Score 8


Because a comes after T in the ASCII character set, but before t.

The decimal ASCII encoding of these letters:

  • T is 84.
  • a is 97.
  • t is 116.



ACCEPTED ANSWER

Score 6


The key insight here is that string comparison doesn't compare based on alphabetical order or any natural order, but instead on the order of the characters in ASCII. You can see this order in an ASCII table.

Python will compare the first character in each string, and if it is the same will move on to the next. It will do this until the characters differ, or one string runs out (in which case the longer string will be considered greater).

As cdhowie pointed out, in a decimal ASCII encoding T is 84, a is 97, and t is 116. Therefore:

>>> 'T' < 'a' < 't'
True

To show our second point:

>>> "apple" > "a"
True

To get a more natural comparison see: Does Python have a built in function for string natural sort?

To answer the question you added in an edit:

The simple answer is "yes". A conversion of 11.1 to '11.1' is being performed.

The more complicated answer deals with how exactly comparison is implemented in python. Python objects can be compared if they implement the Comparison magic methods. There's a fair amount of reading you can do about python internals in that link.

As @glibdup pointed out, the above is incorrect. In python different types are compared based on the name of their type. So, since 'str' > 'float' any string will be greater than any float. Alternatively, any tuple will be greater than any string.