比较Python中的字符串和数字

Ser*_*gey 1 python string comparison numbers

可能重复:
Python如何比较字符串和int?

为什么下面的部分表现得像它的表现?

>>> '10' > 100
True
>>> 100 < '10'
True
Run Code Online (Sandbox Code Playgroud)

它不应该引发例外吗?

jco*_*ado 6

文档:

CPython实现细节:除了数字之外的不同类型的对象按其类型名称排序; 不支持正确比较的相同类型的对象按其地址排序.

所以它只是在CPython('int' < 'str')中发生的事情,但不保证在其他实现中发生.

实际上,python3中已删除此行为:

>>> '10' > 100
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() > int()
>>> 100 < '10'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: int() < str()
Run Code Online (Sandbox Code Playgroud)