转换为二进制并在Python中保持前导零
我试图使用Python中的bin()函数将整数转换为二进制。 但是,它总是删除我实际需要的前导零,这样结果总是8位:
例:
bin(1) -> 0b1
# What I would like:
bin(1) -> 0b00000001
有办法做到这一点吗?
8个解决方案
153 votes
使用0b功能:
>>> format(14, '#010b')
'0b00001110'
0b函数只是按照格式规范迷你语言格式化输入。 #使格式包括0b前缀,并且010大小格式化输出以适合10个字符宽度,具有0填充; 0b前缀为2个字符,其他8为二进制数字。
这是最紧凑和直接的选择。
如果要将结果放在一个更大的字符串中,请使用格式化的字符串文字(3.6+)或使用0b并在占位符#的冒号后面放置0b函数的第二个参数:
>>> value = 14
>>> f'The produced output, in binary, is: {value:#010b}'
'The produced output, in binary, is: 0b00001110'
>>> 'The produced output, in binary, is: {:#010b}'.format(value)
'The produced output, in binary, is: 0b00001110'