这个问题在这里已经有了答案:
How does Python 2 compare string and int? Why do lists compare as greater than numbers, and tuples greater than lists?
(2 个回答)
Ordering of string representations of integers [duplicate]
(6 个回答)
6年前关闭。
我有从 JSON
加载的数值对象,因此都是字符串。
我在与这些字符串进行数值比较时遇到问题。以下内容对我来说毫无意义,我希望你们中的一位冠军能解释一下..
In[2]: print '100' < '45'
True
In[3]: print '99' < '45'
False
使用
Python 2.7
最佳答案
比较字符串时,它们通过字符的 ascii 值进行比较。 '1'
值为 49,'4'
是 52。所以 '1'
是 < '4'
. '9'
但是是 57,所以 '9'
是 > ' 4'
.
如果你想在数字上比较它们,你可以 int()
字符串首先像:
print int('100') < int('45')
关于python数字字符串比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35489619/