2014-01-28 216 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:

似乎遵循最小驚訝好一點的原則了。

相關問題