leading zeros in python [duplicate]

2019-05-26 18:08发布

This question already has an answer here:

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?

2条回答
乱世女痞
2楼-- · 2019-05-26 18:45

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.

查看更多
放荡不羁爱自由
3楼-- · 2019-05-26 18:49

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

查看更多
登录 后发表回答