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
?
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
?
eumiro's answer is better, however I'm just posting this for variety:
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 decimal6
)08
formats the number to eight digits zero-padded on the leftb
converts the number to its binary representationGoing Old School always works
A bit twiddling method...
Just use the format function
The general form is
Just another idea:
Shorter way via string interpolation (Python 3.6+):