使用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'