python - 字符串到 int 的转换错误?

标签 python

<分区>

Possible Duplicate:
Python “is” operator behaves unexpectedly with integers

在 python 2.6.6 中,当我使用 int() 将字符串转换为数字时,如果字符串为 257 或更大,则以下代码的行为不正确。

curr = int("256")  
myint = int("256")  
if curr is myint:  
    print("true")  
else:  
    print("false")  

这会返回正确的 true

curr = int("257")  
myint = int("257")  
if curr is myint:  
    print("true")  
else:  
    print("false")  

这会返回 false ???

最佳答案

您不应该使用 is 来比较整数。请改用 ==

is 应该只用于测试两个变量是否指向同一个对象。在 Python 中,较小的数字会被埋葬,您经常为相同的 int 文字获得相同的对象,但并非总是如此,对于较大的数字也并非如此。

关于python - 字符串到 int 的转换错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13256746/

相关文章:

python - "WHY"2个相同版本的python的不同可执行文件?

python - 在加密字符串 block 的嵌套循环中避免出现 'index not in range'

python - 有没有比 for 循环和 if 语句更快的方法来找到距 python 中另一个点最近的点?

python - 如何在 python 中计算正态分布百分比点函数

python - 如何在 wx.Python 或其他 python gui 窗口中打开 HTML JavaScript 页面?

python - 使用命名(fifo)管道在 python 和 c++ 之间传输数组(图像)

python - 如何在 Python 中定义子模块?

python - 如何在 Python 中使用 Xades-EPES 标准进行签名?

javascript - 为什么 diffbot 在这里看不到价格?

Python 兼容性 : Catching exceptions