What do numbers starting with 0 mean in python?

后端 未结 9 2202
忘掉有多难
忘掉有多难 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 octal numbers (base 8, values 0 - 7)

    You can convert a decimal number to octal with the oct() function.

    In [125]: for i in range(10):
       .....:     print '{:5} {:5}'.format(i, oct(i))
       .....:
        0 0
        1 01
        2 02
        3 03
        4 04
        5 05
        6 06
        7 07
        8 010
        9 011
    

    and convert an octal value to integer with the int() function with the appropriate base (8 in this case):

    int(str(17), 8)
    Out[129]: 15
    

    The similar set of rules/functions apply for hexadecimal numbers (base 16) using the hex() function.

提交回复
热议问题