Python cannot handle numbers string starting with 0. Why?

会有一股神秘感。 提交于 2019-11-26 12:29:50

My guess is that since 012 is no longer an octal literal constant in python3.x, they disallowed the 012 syntax to avoid strange backward compatibility bugs. Consider your python2.x script which using octal literal constants:

a = 012 + 013

Then you port it to python 3 and it still works -- It just gives you a = 25 instead of a = 21 as you expected previously (decimal). Have fun tracking down that bug.

From the Python 3 release notes http://docs.python.org/3.0/whatsnew/3.0.html#integers

Octal literals are no longer of the form 0720; use 0o720 instead.

The 'leading zero' syntax for octal literals in Python 2.x was a common gotcha:

Python 2.7.3
>>> 010
8

In Python 3.x it's a syntax error, as you've discovered:

Python 3.3.0
>>> 010
  File "<stdin>", line 1
    010
      ^
SyntaxError: invalid token

You can still convert from strings with leading zeros same as ever:

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