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
?
>>> '{0:08b}'.format(6)
'00000110'
Just to explain the parts of the formatting string:
{}
places a variable into a string0
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 leftb
converts the number to its binary representationIf you're using a version of Python 3.6 or above, you can also use f-strings:
>>> f'{6:08b}'
'00000110'