I read this question String comparison technique used by Python.
But, i don't know exactly why the comparison '9' < '10' is False
.
Did this happen because '9' is bigger than '1'? because python's string comparison is lexicographic?
I read this question String comparison technique used by Python.
But, i don't know exactly why the comparison '9' < '10' is False
.
Did this happen because '9' is bigger than '1'? because python's string comparison is lexicographic?
Python grabs the first character in the strings and compares them. In this case it starts by comparing if 9
is less than 1
. Since it's not, False
is returned. Comparisons are done using the character codes. (To save you some time looking it up, 1-9 are indeed in numerical order. Something to be careful about is the capital letters are before the lowercase ones, so 'B' < 'a'
returns True
.)
If the comparison were equal, it would move on to the next character and so on.
You can use isnumeric to check if you're comparing 2 numbers, and if you are then change the strings to numbers before comparing.
if a.isnumeric() and b.isnumeric():
if float(a) < float(b):
In lexicographic order "10" comes before "9" that is why it is returning False. If you did
"10" < "9"
You would get True because the string "10" comes before the string "9".