简体   繁体   English

为什么python print(09)给出SyntaxError:无效令牌但没有print(07)?

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

Here is version of Python installed on my system. 这是我的系统上安装的Python版本。

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 不知何故,08、09在8、9时无法理解,但其他数字起作用

>>> 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 不仅打印,而且datetime.date也抛出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). Python 2.x上以0开头(且不跟xb )的整数文字是八进制文字 (为了将来的兼容性, 0o前缀也表示八进制文字,它是Py3中唯一接受的形式,该形式拒绝所有 “普通” 0前缀为int文字,以避免可能尝试C八进制语法的人感到困惑。 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. 八进制只有0到7之间的数字,因此9在八进制中是无意义的,而09明确要求将其解释为八进制,因此是错误。

In short, don't try to pad out your int literals with leading 0 s. 简而言之,不要试图以0开头填充int常量。 It changes the meaning, not just the appearance. 它改变了含义,而不仅仅是外观。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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