问题描述
使用format()
功能:
>>> format(14, '#010b')
'0b00001110'
该format()
函数只是按照Format Specification mini
language对输入进行格式化。使#
格式包含0b
前缀,010
大小格式化输出以适应 10
个字符的宽度,并带有0
填充;0b
前缀2 个字符,其他 8 个二进制数字。
这是最紧凑和最直接的选择。
如果要将结果放在更大的字符串中,请使用格式化的字符串文字(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'
解决方法
我正在尝试使用 Python 中的 bin() 函数将整数转换为二进制。但是,它总是删除我实际需要的前导零,这样结果总是 8 位:
例子:
bin(1) -> 0b1
# What I would like:
bin(1) -> 0b00000001
有没有办法做到这一点?