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?

- 9,839
- 3
- 25
- 46

- 5,234
- 23
- 71
- 81
7 Answers
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'
>>>

- 6,860
- 20
- 39
- 51

- 83,368
- 10
- 76
- 104
-
6What about negative numbers? – Gui13 Jul 25 '13 at 07:14
-
2Surprisingly this appears to be the fastest, but ackkkk. – user3467349 Jan 15 '15 at 22:07
-
@loannis Your edit caused problems because now the wrong result was provided for negative values, -30 != 30 whereas your edit results in `bin(30).lstrip('-0b').zfill(8) == bin(-30).lstrip('-0b').zfill(8)` – Nick is tired Jan 17 '18 at 12:50
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)

- 1
- 1

- 52,368
- 9
- 94
- 137
-
7
-
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 Sep 08 '09 at 22:23
-
Don’t use `str.format()` for a single placeholder and nothing else. That’s what we have `format()` for: `format(30, '08b')` – Martijn Pieters Oct 01 '19 at 20:35
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.

- 12,775
- 6
- 58
- 84
You can use format in Python 2 or Python 3:
>> print( format(15, '08b') )
00001111
[]'s

- 151
- 3
- 8
You can use this too :
bi=bin(n)[2:]
This will remove the '0b'
portion of the returned value and you can use the output anywhere .

- 3,126
- 28
- 25
The current answers don't consider negative values (thanks @Gui13 for the comment!) in which case you get -0b...
instead of just 0b...
. You can handle both with a simple if-else
where the value is checked whether it's less than zero or not
>>> def printBit(x):
if x < 0:
return '-' + bin(x)[3:].zfill(8) # replace
else:
return bin(x)[2:].zfill(8)
>>> print(printBit(30))
'00011110'
>>> print(printBit(-30))
'-00011110'
or by using replace()
>>> print(bin(30)).replace('0b', '').zfill(8)
The problem with the call above is that one of the bits gets "lost" to the -
sign due to the same value being used for the zfill()
. You can handle this too with a simple ternary check:
>>> x = 30
>>> print(bin(x)).replace('0b', '').zfill(9 if x < 0 else 8)
'00011110'
>>> x = -30
>>> print(bin(x)).replace('0b', '').zfill(9 if x < 0 else 8)
'-00011110'
Last but not least you can also make the zfill()
to automatically adapt the number of 0
s to match a byte (8 bits) or a n
number of bit quadruplets (4 bits):
>>> def pb(x):
bres = bin(x).replace('0b', '').replace('-', '') # If no minus, second replace doesn't do anything
lres = len(bres) # We need the length to see how many 0s we need to add to get a quadruplets
# We adapt the number of added 0s to get full bit quadruplets.
# The '-' doesn't count since we want to handle it separately from the bit string
bres = bres = ('-' if x < 0 else '') + bres.zfill(lres + (4-lres%4))
return bres
>>> print(pb(7))
'0111'
>>> print(pb(-7))
'-0111'
>>> print(pb(30))
'00011110'
>>> print(pb(-30))
'-00011110'
Here is the final version with adaptable filling of 0
s and additional split with space every n
characters (where the n
is determined by filling factor):
>>> def pb(x, fillingBits=4, splitWithSpace=True):
# If no minus, second replace doesn't do anything
bres = bin(x).replace('0b', '').replace('-', '')
lres = len(bres)
bres = bres.zfill(lres + (fillingBits - (lres % fillingBits)))
lres = len(bres)
# We can also add a blank after every fillingBits character
if splitWithSpace:
bres = ' '.join([bres[i:(i + fillingBits)] for i in range(0, lres, fillingBits)])
bres = ('-' if x < 0 else '') + bres
# We remove any trailing/leading blanks (occurring whenever splitWithSpace enabled)
return bres.strip()
>>> print(pb(7))
'0111'
>>> print(pb(-7))
'-0111'
>>> print(pb(30))
'0001 1110'
>>> print(pb(-30))
'-0001 1110'

- 8,713
- 7
- 76
- 161
-
Read before acting "smart". The OP clearly asks about padding plus the fact that `bin()` (at least at the time I wrote this answer) does NOT handle two complement and a negative number is returned as `-` followed by the converted binary. The accepted answer even removes the `-`, which makes results in a negative being the same as a positive number. – rbaleksandar Dec 29 '17 at 11:34
python 2.7
print "{0:b}".format(30)
python 3.x
print ('{0:b}'.format(30))

- 87
- 9
-
Both of the snippets will work on python 2.x and both will result in a syntax error on python 3.x, since print is a function in 3.x. Did you perhaps mean to make the second snippet `print("{0:b}".format(30))`? – kristaps Jun 29 '17 at 20:28
-
you're right , i have forget that print in python 3.x is with (), i will it new edit – iratxe Jul 04 '17 at 09:32