python - Python中的字符串与整数比较

标签 python

<分区>

Possible Duplicate:
How does Python compare string and int?

我正在用 Python 做一些比较。我惊讶地发现我可以将字符串与整数进行比较。然后我做了一个 id,发现实际上字符串的 id 大于 int 的 id,我认为这就是我得到这个输出的原因。

In [19]: 'a' < 3
Out[19]: False

In [20]: 'a'>3
Out[20]: True

In [17]: id('a')
Out[17]: 140414909035824

In [18]: id(3)
Out[18]: 23119752

请确认我正确解释了此行为(Python 在 id 级别进行比较)。

最佳答案

Python 2.x 的跨类型比较是一个历史事件。来自documentation :

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

在 Python 3.x 中,这是固定的——这些比较会引发类型错误。

关于python - Python中的字符串与整数比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10461733/

相关文章:

java - 通过传递参数和结果从 Java 调用 Python 代码

python - 更改 python 对象的类(强制转换)

python - 使用 pytest-cov 的类声明缺少测试覆盖率

python - 如何逐个补丁写入 png/tiff 文件?

javascript - 使用 python 脚本打印到 Chrome 控制台 - 如何调整以在 div 中打印?

python - 在 django 中创建字段列表

python - 出于安全目的,将 os.system 替换为 os.popen

python - 如何计算 pandas 中事件之间的时间

python - 使用 beautifulsoup 将 td 标签内的文本与粗体标签分离

javascript - JQuery加载方法中使用post传递数据