Converting integer to binary in python

Smith picture Smith · May 2, 2012 · Viewed 313.8k times · Source

In order to convert an integer to a binary, I have used this code :

>>> bin(6)  
'0b110'

and when to erase the '0b', I use this :

>>> bin(6)[2:]  
'110'

What can I do if I want to show 6 as 00000110 instead of 110?

Answer

eumiro picture eumiro · May 2, 2012
>>> '{0:08b}'.format(6)
'00000110'

Just to explain the parts of the formatting string:

  • {} places a variable into a string
  • 0 takes the variable at argument position 0
  • : adds formatting options for this variable (otherwise it would represent decimal 6)
  • 08 formats the number to eight digits zero-padded on the left
  • b converts the number to its binary representation

If you're using a version of Python 3.6 or above, you can also use f-strings:

>>> f'{6:08b}'
'00000110'