转换为二进制文件并保持Python中前导零 [英] Convert to binary and keep leading zeros in Python
问题描述
示例:
bin(1) - > 0b1
#我想要的是:
bin(1) - > 0b00000001
有没有这样做的方法?
使用 format() function
:
>>>格式(14,'#010b')
'0b00001110'
format()
函数简单地格式化格式规格迷你语言。 #
使格式包括 0b
前缀, 010
size将输出格式化为10个字符的宽度,使用 0
padding; 2个字符为 0b
前缀,另外8个为二进制数字。
这是最紧凑和直接的选项。
如果您要将结果放在更大的字符串中,请使用 ,并把格式的第二个参数()
占位符冒号后面的函数 {:..}
:
>>> '产生的输出是二进制的:{:#010b}'。format(14)
pre>
'产生的输出是二进制的:0b00001110'
如果您不想要
0b
前缀,只需将#
并调整字段的长度:
>>>格式(14,'08b')
'00001110'
I'm trying to convert an integer 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:
Example:
bin(1) -> 0b1 # What I would like: bin(1) -> 0b00000001
Is there a way of doing this?
解决方案Use the
format()
function:>>> format(14, '#010b') '0b00001110'
The
format()
function simply formats the input following the Format Specification mini language. The#
makes the format include the0b
prefix, and the010
size formats the output to fit in 10 characters width, with0
padding; 2 characters for the0b
prefix, the other 8 for the binary digits.This is the most compact and direct option.
If you are putting the result in a larger string, use
str.format()
and put the second argument for theformat()
function after the colon of the placeholder{:..}
:>>> 'The produced output, in binary, is: {:#010b}'.format(14) 'The produced output, in binary, is: 0b00001110'
If you did not want the
0b
prefix, simply drop the#
and adjust the length of the field:>>> format(14, '08b') '00001110'
这篇关于转换为二进制文件并保持Python中前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!