转换为二进制文件并保持Python中前导零 [英] Convert to binary and keep leading zeros in Python

查看:271
本文介绍了转换为二进制文件并保持Python中前导零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



示例:

  bin(1) - > 0b1 

#我想要的是:
bin(1) - > 0b00000001

有没有这样做的方法?

解决方案

使用 format() function

 >>>格式(14,'#010b')
'0b00001110'



format()函数简单地格式化格式规格迷你语言使格式包括 0b 前缀, 010 size将输出格式化为10个字符的宽度,使用 0 padding; 2个字符为 0b 前缀,另外8个为二进制数字。



这是最紧凑和直接的选项。



如果您要将结果放在更大的字符串中,请使用 ,并把格式的第二个参数()占位符冒号后面的函数 {:..}

 >>> '产生的输出是二进制的:{:#010b}'。format(14)
'产生的输出是二进制的:0b00001110'
pre>

如果您不想要 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 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.

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'

If you did not want the 0b prefix, simply drop the # and adjust the length of the field:

>>> format(14, '08b')
'00001110'

这篇关于转换为二进制文件并保持Python中前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆