转换为二进制并保留前导零

新手上路,请多包涵

我正在尝试使用 Python 中的 bin() 函数将整数转换为二进制。但是,它总是删除我实际需要的前导零,这样结果总是 8 位:

例子:

 bin(1) -> 0b1

# What I would like:
bin(1) -> 0b00000001

有没有办法做到这一点?

原文由 Niels Sønderbæk 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

使用 format() 功能

 >>> format(14, '#010b')
'0b00001110'

format() 函数只是按照 格式规范迷你语言 对输入进行格式化。 The # makes the format include the 0b prefix, and the 010 size formats the output to fit in 10 characters width, with 0 填充; 2 个字符为 0b 前缀,另外 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'

原文由 Martijn Pieters 发布,翻译遵循 CC BY-SA 4.0 许可协议

>>> '{:08b}'.format(1)
'00000001'

请参阅: 格式规范迷你语言


注意 Python 2.6 或更早版本,不能省略 : 之前的位置参数标识符,所以使用

>>> '{0:08b}'.format(1)
'00000001'

原文由 bwbrowning 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题