我正在尝试使用 Python 中的 bin() 函数将整数转换为二进制。但是,它总是会删除我实际需要的前导零,这样结果总是 8 位:
例子:
bin(1) -> 0b1
# What I would like:
bin(1) -> 0b00000001
有没有办法做到这一点?
最佳答案
使用 format()
function :
>>> format(14, '#010b')
'0b00001110'
format()
函数只是格式化Format Specification mini language 之后的输入。 . #
使格式包含 0b
前缀,010
大小格式化输出以适应 10 个字符的宽度,其中 0
填充; 0b
前缀的 2 个字符,二进制数字的其他 8 个字符。
这是最简洁直接的选择。
如果您要将结果放在更大的字符串中,请使用 formatted string literal (3.6+) 或使用 str.format()
并将 format()
函数的第二个参数放在占位符 {:..}
:
>>> 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'
碰巧,即使只是格式化单个值(因此无需将结果放入更大的字符串中),使用格式化的字符串文字也比使用 format()
:
>>> import timeit
>>> timeit.timeit("f_(v, '#010b')", "v = 14; f_ = format") # use a local for performance
0.40298633499332936
>>> timeit.timeit("f'{v:#010b}'", "v = 14")
0.2850222919951193
但我只会在紧密循环中的性能很重要的情况下使用它,因为 format(...)
可以更好地传达意图。
如果您不想要 0b
前缀,只需删除 #
并调整字段的长度:
>>> format(14, '08b')
'00001110'
https://stackoverflow.com/questions/16926130/