Python中string和int的比较

首先来看一连串的比较,包含string和string类型的,string和int类型之间的比较。

print "100" < "2"      # True
print "5" > "9"        # False

print "100" < 2        # False
print 100 < "2"        # True

print 5 > "9"          # False
print "5" > 9          # True

有人不免有些疑问:

是否由语言规范决定?
不同主流python实现是否存在差异?
不同版本的Python是否有差异?
首先我们参考手册:

CPython的实现细节:不同类型的对象除了数字类型以它们的类型名字排序,相同类型不合适比较的对象由它们的地址决定排序

当你比较两个相同string,或者int时是按照预期方式来排序的即(字典顺序和整数的排序)。
当我们比较string和int类型时是按照类型名字来排序的,str在字典排序上落后于int,float,long,list,bool。这里有一个特例是:元组(tuple)的排序要高于’str’
0 > ‘foo’
False
[1, 2] > ‘foo’
False
(1, 2) > ‘foo’
True

至于前面的三个问题,根据Mark Byers的回答如下:

这里没有语言规范,语言参考里面说,不同类型的对象比较式不平等的,但始终是任意的。
这个比较难回答,以为出了CPython之外还有其他分支,例如:PyPy.
在3.x的版本中,如果你对不同类型对象进行比较,会抛出一个错误提示。

>>> ’10′ > 5
Traceback (most recent call last):
File “”, line 1, in
’10′ > 5
TypeError: unorderable types: str() > int()

This entry posted in python 基础. Entry Tags: , Bookmark the permalink. 

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>