python compare string_Python如何比較字符串和int?

194

python 2手冊:

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.

CPython實現細節:除了數字之外,不同類型的對象是按它們的類型名稱排序的;不支持適當比較的相同類型的對象按其地址排序。

When you order two strings or two numeric types the ordering is done in the expected way (lexicographic ordering for string, numeric ordering for integers).

當您訂購兩個字符串或兩個數字類型時,排序是按照預期的方式進行的(字符串的字典排序,整數的數字排序)。

When you order a numeric and a non-numeric type, the numeric type comes first.

當您訂購數字類型和非數字類型時,數字類型首先出現。

>>> 5 < 'foo'

True

>>> 5 < (1, 2)

True

>>> 5 < {}

True

>>> 5 < [1, 2]

True

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

One exception is old-style classes that always come before new-style classes.

一個例外是舊式類,它們總是先於新式類出現。

>>> class Foo: pass # old-style

>>> class Bar(object): pass # new-style

>>> Bar() < Foo()

False

Is this behavior mandated by the language spec, or is it up to implementors?

這種行為是由語言規范規定的,還是由實現者決定的?

沒有語言規范。語言參考說:

Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily.

否則,不同類型的對象總是比較不相等,並且順序一致但任意。

So it is an implementation detail.

這是一個實現細節。

Are there differences between any of the major Python implementations?

主要的Python實現之間有什么區別嗎?

I can't answer this one because I have only used the official CPython implementation, but there are other implementations of Python such as PyPy.

我不能回答這個問題,因為我只使用了官方的CPython實現,但是還有其他的Python實現,比如PyPy。

Are there differences between versions of the Python language?

Python語言的版本之間有區別嗎?

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

Python 3。x的行為發生了改變,因此試圖訂購一個整數和一個字符串會引起錯誤:

>>> '10' > 5

Traceback (most recent call last):

File "", line 1, in

'10' > 5

TypeError: unorderable types: str() > int()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值