简体   繁体   中英

Why python print(09) give SyntaxError: invalid token but not print(07)?

Here is version of Python installed on my system.

Python 2.7.14 |Anaconda, Inc.| (default, Oct 16 2017, 17:29:19) 
[GCC 7.2.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.

Somehow, 08, 09 is not understand at 8, 9. But other number work

>>> print(02)
2
>>> print(09)
  File "<stdin>", line 1
    print(09)
           ^
SyntaxError: invalid token
>>> print(08)
  File "<stdin>", line 1
    print(08)
           ^
SyntaxError: invalid token
>>> print(07)
7

Not only print, but datetime.date also throw SyntaxError

>>> import datetime
>>> datetime.date(2017,11,09)
  File "<stdin>", line 1
    datetime.date(2017,11,09)
                           ^
SyntaxError: invalid token
>>> datetime.date(2017,11,04)
datetime.date(2017, 11, 4)
>>> 

Integer literals on Python 2.x that begin with 0 (and aren't followed by x or b ) are octal literals (for future compatibility, the 0o prefix also means an octal literal, and it's the only form accepted in Py3, which rejects all "plain" 0 prefixed int literals to avoid confusion from people who might try the C octal syntax). Octal only has digits from 0 to 7, so 9 is nonsensical in octal, and 09 is explicitly requesting it be interpreted as octal, thus the error.

In short, don't try to pad out your int literals with leading 0 s. It changes the meaning, not just the appearance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM