Comparing Python strings with different cases and float

why python gives output like this:

>>> 'apple' > 'T' True >>> 'apple' > 't' False 

It must be true for both cases. right?

Edit:

I have an idea of ​​an ASCII table. Thanks!

Now how about this. Is 11.1 considered "11.1"?

 >>> 'apple' > 11.1 True 
+4
source share
2 answers

The key insight here is that string comparisons are not compared based on alphabetical order or any natural order, but instead in character order in ASCII. This order can be seen in the ASCII table.

Python will compare the first character on each line, and if it is the same, it will move on to the next. He will do this until the characters differ, or one line ends (in this case, a longer line will be considered larger).

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

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

To show our second point:

 >>> "apple" > "a" True 

For a more natural comparison, see Does Python have a built-in function for naturally sorting strings?

To answer the question that you added in editing:

The simple answer is yes. Converts 11.1 to '11.1' .

A more complicated answer concerns how exactly the comparison is done in python. Python objects can be compared if they implement comparison comparison methods . In this link you can read information about the internal components of python.

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

+6
source

Because a appears after T in the ASCII character set, but before T

Decimal ASCII encoding of these letters:

  • T - 84.
  • a - 97.
  • T - 116.
+8
source

Source: https://habr.com/ru/post/1440393/


All Articles