I am using the python shell to figure out how the print command works in python.
When I type in
print 01
1
print 010
8
print 0100
64
print 030
24
What's going on here? Is it just base 2? Why does the "one" in the second position print as 8? Shouldn't it be 2 if it's binary?
-
possible duplicate of Integer with leading zeroesCameron Skinner– Cameron Skinner2010年12月19日 22:48:35 +00:00Commented Dec 19, 2010 at 22:48
-
Not exact duplicate, but close enough. Python and Java behave the same way in this respect.Cameron Skinner– Cameron Skinner2010年12月19日 22:49:01 +00:00Commented Dec 19, 2010 at 22:49
-
2Python is quite different here in that this syntax is deprecated, and there are better ones. So I think it's better to keep it separate.Lennart Regebro– Lennart Regebro2010年12月19日 22:57:29 +00:00Commented Dec 19, 2010 at 22:57
-
@Lennart: Fair enough. Didn't know it has been deprecated. Hopefully Java 7 will do the same!Cameron Skinner– Cameron Skinner2010年12月20日 12:54:44 +00:00Commented Dec 20, 2010 at 12:54
8 Answers 8
Starting a number with a zero marks it as octal in Python 2. This has been recognized as confusing, surprising and also inconsistent, as starting with 0x will mark it as hexadecimal. Therefore, in Python 3, starting with 0 is invalid, and you get octal by starting with 0o. You can also start with 0b to mark it as binary.
>>> 10
10
>>> 0x10
16
>>> 0o10
8
>>> 0b10
2
>>> 010
File "<stdin>", line 1
010
^
SyntaxError: invalid token
0x, 0o and 0b also works in Python 2.6 and Python 2.7.
Comments
That's the old notation for octal numbers in Python.
In Python 2.6 and newer you should use the syntax 0o10 for octal and 0b10010 for binary numbers.
In older versions of Python you enter binary numbers as strings and parse them to integers:
>>> x = int("10010", 2)
>>> print x
18
Comments
When you append 0 to the left of the number, it is interpreted as an octal number. So 10 in octal equals 8 in decimal, and 100 in octal equals 64 in decimal and so on.
If you want to deal with binary number, you should use bit-wise operators to play with the bits.
Comments
Like in most programming languages, Python follows the C tradition of numbers starting with 0 being octal (base 8) numbers.
Comments
It's interpreting them as octal (base 8) numbers, not binary.
Comments
Definitely not base2. It's Octal - base 8.
Comments
Numbers starting with 0 are interpreted as octal. For binary numbers the 'start sequence' is 0b.
>>> print 0b10
2
>>> print 010
8
>>> print 0x10
16