Converting integer to binary in python

2019-01-02 16:35发布

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?

8条回答
若你有天会懂
2楼-- · 2019-01-02 17:36

.. or if you're not sure it should always be 8 digits, you can pass it as a parameter:

>>> '%0*d' % (8, int(bin(6)[2:]))
'00000110'
查看更多
千与千寻千般痛.
3楼-- · 2019-01-02 17:37

('0' * 7 + bin(6)[2:])[-8:]

or

right_side = bin(6)[2:] '0' * ( 8 - len( right_side )) + right_side

查看更多
登录 后发表回答