问题描述
使用format()
功能:
>>> format(14, '#010b')
'0b00001110'
该format()
函数仅遵循格式规范迷你语言来格式化输入。在#
使格式包括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
有办法吗?