leading zeros in python [duplicate]

2019-05-26 18:38发布

问题:

This question already has an answer here:

  • What do numbers starting with 0 mean in python? 9 answers

Python seems to be able to accept leading zeros for any number except 08 or 09. For instance,

a = 04

works in the interpreter but

a = 08

returns

SyntaxError: invalid token

I'm using python 2.7.3 on OSX, and others have been able to duplicate the error. What gives?

回答1:

Numbers with a leading zero in them are interpreted as octal, where the digits 8 and 9 don't exist.

It's worse in Python 3, leading zeros are a syntax error no matter which digits you use. See What’s New In Python 3.0 under "New octal literals". Also PEP 3127.



回答2:

When you start a number with a 0, Python sees it as an octal. So while yes, octal 04 is equal to decimal 04, but octal 08 does not even exist (because octal digits can only be in the range [0,7]).

Found here: Python: Invalid Token