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

前端 未结 4 407
眼角桃花
眼角桃花 2021-01-14 18:14

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

4条回答
  •  误落风尘
    2021-01-14 18:52

    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 "", 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.

提交回复
热议问题