Why does Python change the value of an integer when there is a 0 in front of it?

孤人 提交于 2019-12-01 07:19:46

问题


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 

Now, I've tried to debug it, and the the integer I've passed in has indeed turned out to be 659.

Why does this happen and how can I get python to ignore leading zeros of the integer literal?


Here's the code for my function:

def intToStr(i):
    digits = '0123456789'
    if i == 0:
        return 0
    result = ""
    while i > 0:
        result = digits[i%10] + result
        i /= 10
    return result

回答1:


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

This way you will explicitly force the conversion to base 10. And int wont be inferring it for you.




回答2:


An integer literal starting with a 0 is interpreted as an octal number, base 8:

>>> 01223
659

This has been changed in Python 3, where integers with a leading 0 are considered errors:

>>> 01223
  File "<stdin>", line 1
    01223
        ^
SyntaxError: invalid token
>>> 0o1223
659

You should never specify an integer literal with leading zeros; if you meant to specify an octal number, use 0o to start it, otherwise strip those zeros.




回答3:


Numbers that start with a 0 are interpreted as octal numbers. If it starts with 0x it's hexa decimal.




回答4:


A leading zero causes Python to interpret your number as octal (base-8).

To strip out the zeros (assuming num is a string), do:

num.lstrip("0")


来源:https://stackoverflow.com/questions/13195202/why-does-python-change-the-value-of-an-integer-when-there-is-a-0-in-front-of-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!