python数字字符串比较 [英] python numeric string comparison

查看:388
本文介绍了python数字字符串比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有从 JSON 对象加载的数值,因此都是字符串。

I have numerical values that are loaded from a JSON object and are therefore all strings.

我在对这些字符串进行数值比较时遇到问题。以下内容对我来说毫无意义,我希望你们中的一位冠军能解释一下。.

I am having issues with making numerical comparisons with these strings. The following makes no sense to me and I was hoping one of you champions could explain..

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'

When comparing strings they're compared by the ascii value of the characters. '1' has a value 49, and '4' is 52. So '1' is < '4'. '9' however is 57, so '9' is > '4'.

如果要对它们进行数字比较,可以先将字符串 int()例如:

If you want to compare them numerically you could just int() the strings first like:

print int('100') < int('45')

这篇关于python数字字符串比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆