2014-01-28 57 views
3

如何检查字符串> int评估为True?为什么string> int评估为True?

>>> strver = "1" 
>>> ver = 1 
>>> strver > ver 
True 
>>> strVer2 = "whaat" 
>>> strVer2 > ver 
True 

做了更多一些尝试:

>>> ver3 = 0 
>>> strVer2 > ver3 
True 

我觉得应该有尝试比较时的错误,但它好像没有什么是用来处理这样的错误,或assert应使用但如果使用-O标志运行python代码,可能会很危险!

+2

有一个很好的答案类似的问题:http://stackoverflow.com/questions/3270680/how-does-python-compare-string-and-int –

+0

这只是一个猜测在这里,但我会说这种行为是存在的,以便可以将字符串和整数都放在有序容器中(这要求对元素进行排序,因此这些元素必须具有可比性)。所以我猜想有人认为字符串的排名高于int,无论他们的价值如何。 – ereOn

+1

“我认为应该有一个错误” - 开发人员同意!他们改变了行为,在Python 3中引发了一个TypeError。 – user2357112

回答

9

来源:How does Python compare string and int?,这反过来又引用了CPython的manual

CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.

由如此回​​答:

When you order two incompatible types where neither is numeric, they are ordered by the alphabetical order of their typenames:

>>> [1, 2] > 'foo' # 'list' < 'str' 
False 
>>> (1, 2) > 'foo' # 'tuple' > 'str' 
True 

>>> class Foo(object): pass 
>>> class Bar(object): pass 
>>> Bar() < Foo() 
True 

...所以,这是因为 'S' 来后'我'在字母表中!幸运的是,虽然,这有点奇怪的行为已经在Python 3.X实施“固定”:

In Python 3.x the behaviour has been changed so that attempting to order an integer and a string will raise an error:

似乎遵循最小惊讶好一点的原则了。

相关问题