蟒蛇转换为二进制,并保持前导零 [英] python convert to binary and keep leading zeros
问题描述
我想转换为int使用Python中的bin()函数的二进制文件。然而,它始终删除前导零,这是我真正需要的,这样的结果始终是8位:
I'm trying to convert an int to binary using the bin() function in python. However, it always removes the leading zeros, which I actually need, such that the result is always 8-bit:
例如:
bin(1) -> 0b1
# what I would like:
bin(1) -> 0b00000001
有谁知道这样做的方法吗?
Does anybody know a way of doing this?
推荐答案
使用 格式()
功能:
>>> format(14, '#010b')
'0b00001110'
的格式()
函数只是格式化输入下面的的格式规范迷你语言。在#
使得格式包括 0B
preFIX,而 010
尺寸格式的输出,以适应10个字符的宽度,用 0
填充; 2个字符 0B
preFIX,其他8为二进制数字。
The format()
function simply formats the input following the Format Specification mini language. The #
makes the format include the 0b
prefix, and the 010
size formats the output to fit in 10 characters width, with 0
padding; 2 characters for the 0b
prefix, the other 8 for the binary digits.
这是最紧凑和直接的选择。
This is the most compact and direct option.
如果你把结果在一个更大的字符串,请使用 海峡.format()
并把第二个参数为格式()
占位符 {:..}
:
If you are putting the result in a larger string, use str.format()
and put the second argument for the format()
function after the colon of the placeholder {:..}
:
>>> 'The produced output, in binary, is: {:#010b}'.format(14)
'The produced output, in binary, is: 0b00001110'
如果你不想让 0B
preFIX,只要简单地把#
并调整的长度现场:
If you did not want the 0b
prefix, simply drop the #
and adjust the length of the field:
>>> format(14, '08b')
'00001110'
这篇关于蟒蛇转换为二进制,并保持前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!