为什么string>int的计算结果为True?

2024-10-03 00:18:20 发布

您现在位置:Python中文网/ 问答频道 /正文

检查字符串int>;如何实现?你知道吗

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

做了更多的实验:

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

我认为在尝试比较时应该有一个错误,但似乎没有生成任何东西来处理这样的错误,或者应该使用assert,但是如果python代码是用-O标志运行的,那么这可能是危险的!你知道吗


Tags: 字符串代码gttrue标志错误assertint
1条回答
网友
1楼 · 发布于 2024-10-03 00:18:20

来源:How does Python compare string and int?,它反过来引用了CPythonmanual

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”在“i”之后!不过,幸运的是,在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:

现在似乎遵循最小惊奇的原则好一点了。你知道吗

相关问题 更多 >