How can I make `bin(30)` return `00011110` instead of `0b11110`? [duplicate]
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'
>>>
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)
Take advantage of the famous format()
function with the lesser known second argument and chain it with zfill()
'b'
- Binary
'x'
- Hex
'o'
- Octal
'd'
- Decimal
>>> print format(30, 'b')
11110
>>> print format(30, 'b').zfill(8)
00011110
Should do. Here 'b'
stands for binary just like 'x'
, 'o'
& 'd'
for hexadecimal, octal and decimal respectively.
You can use format in Python 2 or Python 3:
>> print( format(15, '08b') )
00001111
[]'s