Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

What do numbers starting with 0 mean in python?

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

I'm using Python 2.7.3. I have tested this in Python 3.0, and apparently this is now an error. So it is something version-specific.

They are apparently still integers:

>>> type(027)
<type 'int'>
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?81 + 1?8? = 9,

0100 is equal to 1?82 + 0?81 + 0?8? = 64,

027 is equal to 2?81 + 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?81 + 1?8? = 9,

0o100 is equal to 1?82 + 0?81 + 0?8? = 64,

0o27 is equal to 2?81 + 7?8? = 16 + 7 = 23.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...