when python compare operator in string. How does it work?
"1.0.3" > "1.0.0" return true
"1.0.3" > "1.0.6" return false
I heard it is using ascii code.
Anyone please detail explain this Issue.
thank U.
When comparing strings this way, you are comparing whether a string comes before or after the other string if they were sorted alphabetically.
"a" < "b" # True - a is earlier in the alphabet than b
"b" < "a" # False
The same thing is happening with your decimals - but it can lead to undesirable results;
11 < 2 # True - 11 is larger than 2.
"11" < "2" # False
This is because the first 'letter' of the 'word' is 1
- which is lower than the first 'letter' of the other 'word' - 2
.
There are some libraries out there such as natsort that seek to address this problem - so you may need to look into that when using numbers like that ones you have above that are multiple points (making them invalid decimal numbers).
Python uses lexicographic ordering, meaning that the first character's of each string are compared and if they differ then a result is concluded. If they are the same value, then it will compare the second character and so on until the end of the string.
In Python 3 the the Unicode code point number is used to compare characters. In Python2 it uses the ASCII value of the character.
You can see how this works with an example using the ord
and chr
methods which convert integers to characters and vice versa.
a = "1.0.3"
b = "1.0.6"
for i, v in enumerate(a):
print('a[{}] == "{}" == {}'.format(i, v, ord(v)))
print('b[{}] == "{}" == {}'.format(i, b[i], ord(b[i])))
if v == b[i]:
print('a[{}] is equal to b[{}]'.format(i, i))
if v > b[i]:
print('a[{}] is greater than b[{}]'.format(i, i))
if v < b[i]:
print('a[{}] is less than b[{}]'.format(i, i))
a[0] == "1" == 49
b[0] == "1" == 49
a[0] is equal to b[0]
a[1] == "." == 46
b[1] == "." == 46
a[1] is equal to b[1]
a[2] == "0" == 48
b[2] == "0" == 48
a[2] is equal to b[2]
a[3] == "." == 46
b[3] == "." == 46
a[3] is equal to b[3]
a[4] == "3" == 51
b[4] == "6" == 54
a[4] is less than b[4]
Therefore a < b == True