为什么Python在前面有0时会改变整数的值? [英] Why does Python change the value of an integer when there is a 0 in front of it?
问题描述
我实现了一个函数,将整数转换为字符串 intToStr()
(下面的代码)。
I implemented a function converting an integer number to its representation as a string intToStr()
(code below).
为了测试,我传入了一些值并观察到意外的输出:
For testing I've passed in some values and observed an unexpected output:
print intToStr( 1223) # prints 1223 as expected
print intToStr(01223) # prints 659, surprisingly
现在,我已经试图调试它,我传入的整数确实是 659
。
Now, I've tried to debug it, and the the integer I've passed in has indeed turned out to be 659
.
为什么会发生这种情况?如何让python忽略整数字的前导零?
Why does this happen and how can I get python to ignore leading zeros of the integer literal?
这是我的函数的代码:
def intToStr(i):
digits = '0123456789'
if i == 0:
return 0
result = ""
while i > 0:
result = digits[i%10] + result
i /= 10
return result
推荐答案
正如其他人所说的那样是因为八进制数。但我强烈建议您将功能更改为:
As others have said that's because of octal numbers. But I strongly suggest you to change your function to:
>>> from functools import partial
>>> force_decimal = partial(int, base=10)
>>> force_decimal("01")
1
>>> force_decimal("0102301")
102301
这样你就明确强制转换为base 10.并且int不会为你推断它。
This way you will explicitly force the conversion to base 10. And int wont be inferring it for you.
这篇关于为什么Python在前面有0时会改变整数的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!