简体   繁体   中英

Why isn't 0-padding allowed in Python?

I've just noticed 0-padding is not allowed in Python and I was wondering why this choice was made?

For example:

a = 09

doesn't work while

a = 9

does

How's that?!

Thank you very much for your answers!

Python, as many other languages, treat numbers starting with 0 as being in octal notation. 09 is not valid as octal

See chapter 2.4.4 in the python language reference.

To expand on what @nos said:

>>> a = 01
>>> a
1
>>> a = 07
>>> a
7
>>> a = 010
>>> a
8
>>> a = 08
  File "<stdin>", line 1
    a = 08
         ^
SyntaxError: invalid token

So, a = 010 is octal 10 , which is decimal 8. Octal only knows digits 0 through 7. So that is why this isn't possible.

It's because numbers starting with 0 are octal numbers, and octal figures go from 0 to 7!

Doing a = 07 is perfectly accepted, as an octal; so a = 061 will lead a to contain 49.

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