What do numbers starting with 0 mean in python?

后端 未结 9 2189
忘掉有多难
忘掉有多难 2020-11-22 05:34

When I type small integers with a 0 in front into python, they give weird results. Why is this?

>>> 011
9
>>> 0100
64
>>> 027
23
<         


        
9条回答
  •  执念已碎
    2020-11-22 05:41

    These are numbers represented in base 8 (octal numbers). Some examples:

    Python 2 (old format)

    Note: these forms only work on Python 2.x.

    011 is equal to 1⋅8¹ + 1⋅8⁰ = 9,

    0100 is equal to 1⋅8² + 0⋅8¹ + 0⋅8⁰ = 64,

    027 is equal to 2⋅8¹ + 7⋅8⁰ = 16 + 7 = 23.

    Python 3 (new format)

    In Python 3, one must use 0o instead of just 0 to indicate an octal constant, e.g. 0o11 or 0o27, etc. Python 2.x versions >= 2.6 supports both the new and the old format.

    0o11 is equal to 1⋅8¹ + 1⋅8⁰ = 9,

    0o100 is equal to 1⋅8² + 0⋅8¹ + 0⋅8⁰ = 64,

    0o27 is equal to 2⋅8¹ + 7⋅8⁰ = 16 + 7 = 23.

提交回复
热议问题