我正在尝试使用Python中的bin()函数将整数转换为二进制。但是,它总是删除前导零,这是我实际需要的,这样结果总是8位的:
示例:
bin(1) -> 0b1
# What I would like:
bin(1) -> 0b00000001
有没有办法做到这一点?
发布于 2013-06-05 03:54:39
>>> format(14, '#010b')
'0b00001110'
format()
函数只是根据Format Specification mini language对输入进行格式化。#
使格式包含0b
前缀,010
大小使用0
填充格式化输出以适应10个字符的宽度;2个字符用于0b
前缀,另外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'
发布于 2015-12-11 06:58:00
我正在使用
bin(1)[2:].zfill(8)
将打印
'00000001'
发布于 2017-01-01 22:02:03
有时你只想要一个简单的一行:
binary = ''.join(['{0:08b}'.format(ord(x)) for x in input])
Python 3
https://stackoverflow.com/questions/16926130
复制相似问题