本问题已经有最佳答案,请猛点这里访问。
在bin(30)的输出中," b"代表什么:" 0b11110"? 有什么办法可以摆脱这个" b"? 如何获取bin()的输出以始终返回标准的8位数字输出?
使用zfill():
Return the numeric string left filled with zeros in a string of length width. A sign prefix is handled correctly. The original string is returned if width is less than len(s).
1
2
3>>> bin(30)[2:].zfill(8)
'00011110'
>>>
那负数呢?
出人意料的是,这似乎是最快的,但是肯定。
@loannis您的编辑引起了问题,因为现在为负值提供了错误的结果-30!= 30,而您的编辑结果为bin(30).lstrip(-0b).zfill(8) == bin(-30).lstrip(-0b).zfill(8)
0b就像0x一样-表示数字采用二进制格式(0x表示数字采用十六进制)。
请参阅如何在python中表达二进制文字?
参见http://docs.python.org/dev/whatsnew/2.6.html#pep-3127-integer-literal-support-and-syntax
要剥离0b,最简单的方法是使用字符串切片:bin(30)[2:]
同样,格式为8个字符宽:
1('00000000'+bin(30)[2:])[-8:]
另外,您也可以使用字符串格式化程序(在2.6+中)一步完成所有操作:
1"{0:08b}".format(30)
为string.format答案+1,击败我
对于这种情况,我更喜欢使用内置函数而不是format方法:format(30,08b)而不是" {0:08b}"。format(30)
请勿将str.format()用于单个占位符,请勿使用其他任何占位符。这就是format()的用途:format(30, 08b)
利用鲜为人知的第二个参数利用著名的format()函数并将其与zfill()链接
'b'-二进制
'x'-十六进制
'o'-八进制
'd'-十进制
1
2
3
4>>> print format(30, 'b')
11110
>>> print format(30, 'b').zfill(8)
00011110
应该做。此处'b'代表二进制,就像'x','o'和'd'分别代表十六进制,八进制和十进制。
您也可以使用:
1bi=bin(n)[2:]
这将删除返回值的'0b'部分,您可以在任何地方使用输出。
您可以在Python 2或Python 3中使用格式:
1
2>> print( format(15, '08b') )
00001111
[]的
python 2.7
打印" {0:b}"。格式(30)
python 3.x
打印('{0:b}'。format(30))
这两个代码片段都可以在python 2.x上运行,并且都将在python 3.x上导致语法错误,因为print是3.x中的函数。您可能是想制作第二个片段print("{0:b}".format(30))吗?
您的权利,我忘记了python 3.x中的打印带有(),我将对其进行新的编辑
当前答案不考虑负值(感谢@ Gui13!),在这种情况下,您会得到-0b...而不是0b...。您可以使用简单的if-else来处理这两种情况,其中将检查值是否小于零
1
2
3
4
5
6
7
8
9
10>>> def printBit(x):
if x < 0:
return '-' + bin(x)[3:].zfill(8) # replace
else:
return bin(x)[2:].zfill(8)
>>> print(printBit(30))
'00011110'
>>> print(printBit(-30))
'-00011110'
或使用replace()
1>>> print(bin(30)).replace('0b', '').zfill(8)
上面的调用的问题在于,由于用于zfill()的值相同,所以其中一位被"丢失"到-符号。您也可以通过简单的三元检查来处理此问题:
1
2
3
4
5
6
7>>> x = 30
>>> print(bin(x)).replace('0b', '').zfill(9 if x < 0 else 8)
'00011110'
>>> x = -30
>>> print(bin(x)).replace('0b', '').zfill(9 if x < 0 else 8)
'-00011110'
最后但并非最不重要的一点是,您还可以使zfill()自动适应0的数量以匹配一个字节(8位)或n数量的四位字节(4位):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17>>> def pb(x):
bres = bin(x).replace('0b', '').replace('-', '') # If no minus, second replace doesn't do anything
lres = len(bres) # We need the length to see how many 0s we need to add to get a quadruplets
# We adapt the number of added 0s to get full bit quadruplets.
# The '-' doesn't count since we want to handle it separately from the bit string
bres = bres = ('-' if x < 0 else '') + bres.zfill(lres + (4-lres%4))
return bres
>>> print(pb(7))
'0111'
>>> print(pb(-7))
'-0111'
>>> print(pb(30))
'00011110'
>>> print(pb(-30))
'-00011110'
这是最终版本,其中0可以自适应填充,并且每个n字符之间都有空格分隔(其中n由填充因子确定):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24>>> def pb(x, fillingBits=4, splitWithSpace=True):
# If no minus, second replace doesn't do anything
bres = bin(x).replace('0b', '').replace('-', '')
lres = len(bres)
bres = bres.zfill(lres + (fillingBits - (lres % fillingBits)))
lres = len(bres)
# We can also add a blank after every fillingBits character
if splitWithSpace:
bres = ' '.join([bres[i:(i + fillingBits)] for i in range(0, lres, fillingBits)])
bres = ('-' if x < 0 else '') + bres
# We remove any trailing/leading blanks (occurring whenever splitWithSpace enabled)
return bres.strip()
>>> print(pb(7))
'0111'
>>> print(pb(-7))
'-0111'
>>> print(pb(30))
'0001 1110'
>>> print(pb(-30))
'-0001 1110'
演戏前要"聪明"。 OP显然询问填充以及bin()(至少在我写此答案时)不处理两个补码的事实,并且返回的负数作为-,后跟转换后的二进制。接受的答案甚至删除了-,这使得负数与正数相同。