tags:

views:

280

answers:

2

What does the "b" stand for in the output of bin(30): "0b11110". Is there any way I can get rid of this "b". How can I get the output of bin() to always return a standard 8 digit output?

Thank you,

+12  A: 

0b is like 0x - it indicates the number is formatted in binary (0x indicates the number is in hex).

See How do you express binary literals in python?

See http://docs.python.org/dev/whatsnew/2.6.html#pep-3127-integer-literal-support-and-syntax

To strip off the 0b it's easiest to use string slicing: bin(30)[2:]

And similarly for format to 8 characters wide:

('00000000'+bin(30)[2:])[-8:]

Alternatively you can use the string formatter (in 2.6+) to do it all in one step:

"{0:08b}".format(30)
Douglas Leeder
+1 for `string.format` answer, beat me to it
TokenMacGuy
For this case I prefer the format built in function instead of the format method: format(30, '08b') as opposed to "{0:08b}".format(30)
Manuel Ceron
+6  A: 

Using zfill():

Return the numeric string left filled with zeros in a string of length width. A sign prefix is handled correctly. The original string is returned if width is less than len(s).

>>> bin(30)[2:].zfill(8)
'00011110'
>>>
gimel