简体   繁体   中英

Strings in mathematical operation in python

I was having some problems with my code , a statement was giving true when it should've been false

For some reason '6' > '14' was true. I changed them into int s instead of str s and the problem was solved but i was wondering why this has happened in the first place

here's a picture !( http://prntscr.com/o1c7na )!

For comparing strings it compares char by char, the first char '6' has a greater ASCII representation that '1' hence it is bigger.

Here some examples of the behaviour:

>>> "a" > "b"
False
>>> "a" > "aaa"
False
>>> "1" > "2"
False
>>> "12" > "1"
True
>>> "6" > "14"
True
>>> "6" > "1"
True

The ASCII code can be retrieve with ord :

>>> ord("6")
54
>>> ord("1")
49

This happens because the ascii string comparison happens with ascii code comparison of each letter one by one. So in the 1st step 6 is compared to 1 and since 6 is > 1 it returns true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM