问题:转换为二进制并在Python中保持前导零

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

例:

bin(1) -> 0b1

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

有办法吗?

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?


回答 0

使用format()功能

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

format()函数仅遵循格式规范迷你语言来格式化输入。在#使格式包括0b前缀,而010大小格式的输出,以适应在10个字符宽,与0填充; 2个字符0b前缀,其他8个二进制数字。

这是最紧凑,最直接的选择。

如果将结果放入较大的字符串中,请使用格式化的字符串文字(3.6+)或使用并将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'

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 an formatted string literal (3.6+) or use and put the second argument for the format() function after the colon of the placeholder {:..}:

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

As it happens, even for just formatting a single value (so without putting the result in a larger string), using a formatted string literal is faster than using 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

But I’d use that only if performance in a tight loop matters, as format(...) communicates the intent better.

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

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

回答 1

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

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


请注意,对于python 2.6或更早版本,您不能在之前省略位置参数标识符:,因此请使用

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

See: Format Specification Mini-Language


Note for Python 2.6 or older, you cannot omit the positional argument identifier before :, so use

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

回答 2

我在用

bin(1)[2:].zfill(8)

将打印

'00000001'

I am using

bin(1)[2:].zfill(8)

will print

'00000001'

回答 3

您可以使用字符串格式的迷你语言:

def binary(num, pre='0b', length=8, spacer=0):
    return '{0}{{:{1}>{2}}}'.format(pre, spacer, length).format(bin(num)[2:])

演示:

print binary(1)

输出:

'0b00000001'

编辑: 基于@Martijn Pieters的想法

def binary(num, length=8):
    return format(num, '#0{}b'.format(length + 2))

You can use the string formatting mini language:

def binary(num, pre='0b', length=8, spacer=0):
    return '{0}{{:{1}>{2}}}'.format(pre, spacer, length).format(bin(num)[2:])

Demo:

print binary(1)

Output:

'0b00000001'

EDIT: based on @Martijn Pieters idea

def binary(num, length=8):
    return format(num, '#0{}b'.format(length + 2))

回答 4

使用Python时>= 3.6,最干净的方法是使用带字符串格式的f 字符串

>>> var = 23
>>> f"{var:#010b}"
'0b00010111'

说明:

  • var 要格式化的变量
  • : 之后的所有内容都是格式说明符
  • #使用其他形式(添加0b前缀)
  • 0 用零填充
  • 10 填充到总长度不超过10(包括2个字符 0b
  • b 使用二进制表示形式

When using Python >= 3.6, the cleanest way is to use f-strings with string formatting:

>>> var = 23
>>> f"{var:#010b}"
'0b00010111'

Explanation:

  • var the variable to format
  • : everything after this is the format specifier
  • # use the alternative form (adds the 0b prefix)
  • 0 pad with zeros
  • 10 pad to a total length off 10 (this includes the 2 chars for 0b)
  • b use binary representation for the number

回答 5

有时,您只需要一个简单的班轮:

binary = ''.join(['{0:08b}'.format(ord(x)) for x in input])

Python 3

Sometimes you just want a simple one liner:

binary = ''.join(['{0:08b}'.format(ord(x)) for x in input])

Python 3


回答 6

你可以用这样的东西

("{:0%db}"%length).format(num)

You can use something like this

("{:0%db}"%length).format(num)

回答 7

您可以使用python语法的rjust字符串方法:string.rjust(length,fillchar)fillchar是可选的

对于您的问题,您可以这样写

'0b'+ '1'.rjust(8,'0)

因此它将是“ 0b00000001”

you can use rjust string method of python syntax: string.rjust(length, fillchar) fillchar is optional

and for your Question you acn write like this

'0b'+ '1'.rjust(8,'0)

so it wil be ‘0b00000001’


回答 8

您可以使用zfill:

print str(1).zfill(2) 
print str(10).zfill(2) 
print str(100).zfill(2)

印刷品:

01
10
100

我喜欢这种解决方案,因为它不仅在输出数字时有用,而且在需要将其分配给变量时也有帮助…例如-x = str(datetime.date.today()。month).zfill(2)将在2月中,将x返回为“ 02”。

You can use zfill:

print str(1).zfill(2) 
print str(10).zfill(2) 
print str(100).zfill(2)

prints:

01
10
100

I like this solution, as it helps not only when outputting the number, but when you need to assign it to a variable… e.g. – x = str(datetime.date.today().month).zfill(2) will return x as ’02’ for the month of feb.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。