What do numbers starting with 0 mean in python?

后端 未结 9 2081
忘掉有多难
忘掉有多难 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:53

    They are apparently octal (base 8) numbers, and the 0 is just an outdated prefix that Python 2 used to use.

    In Python 3 you must write: 0o11 instead.

    They are still integers but doing operations with them will give a result in regular base-10 form.

    0 讨论(0)
  • 2020-11-22 05:54

    Both Python versions 2 & 3 understand octal written with leading '0o' and '0O' (Uppercase o), so be in the habit of using if when working with Python 2.x as well.

    Only use leading zeros in numbers in strings.

    You can convert integers from any of the other base systems with int().

    >>> int(0o20)

    16
    

    If you want your output to display with leading zeros, then define it per this answer: Display number with leading zeros

    If you ever plan to work with ZIP Codes, it's best to treat them as strings in all ways.

    0 讨论(0)
  • 2020-11-22 06:00

    In Python 2 (and a few more programming languages), these represent octal numbers.

    In Python 3, 011 no longer works and you would use 0o11 instead.

    In response to edit: and they are regular integers. They are just specified different way; and they are automatically converted by Python to an internal integer representation (which is base-2 actually, so both 9 and 011 are internally converted to 0b1001).

    0 讨论(0)
提交回复
热议问题