我有一個將字符轉換為二進制的函式
def binary(value):
return ''.join(format(ord(i), 'b') for i in value)
print(binary('a')) # 1100001
print(binary('b')) # 1100010
但是當我給多個字符時,它們被連接在一起
print(binary('ab')) # 11000011100010
我想找到一種方法將這些拆分成單獨的字母。例如
'11000011100010' -> '1100001 1100010'
uj5u.com熱心網友回復:
最好的方法是將所有生成的二進制檔案存盤在一個串列中,然后加入所有專案。
output=[]
def binary(a):
binary = ''.join(format(ord(i), '08b') for i in a)
#print(binary)
output.append(binary)
def split_string(a):
for i in a:
binary(i)
split_string('ram')
print("output: ", ' '.join(map(str,output)))
您將獲得如下所示的輸出。
output: 01110010 01100001 01101101
uj5u.com熱心網友回復:
您會丟失任何間距資訊''.join。相反,格式化每個字符,然后再加入。
def binary(value):
for c in value:
yield format(ord(c), 'b')
print(' '.join([x for x in binary('ab')]))
# '1100001 1100010'
uj5u.com熱心網友回復:
您的二進制序列的長度是僅表示數字所需的位數(在這兩種情況下都是 7) - 但它們的長度可能非常不同。您在 ''.join() 呼叫中丟棄了該資訊,并且無法檢索該資訊。為什么不回傳一個字串串列,而不是將它們全部連接起來?
IE:
# when passed value='ab', this will compute the binary representation of 'a'
# and then 'b', both 7 bits, and combine them into a single string of bits,
# 14 characters long; however the fact that these strings were both 7
# characters long gets lost (could have been 6 8, 8 6, etc.)
def binary(value):
return ''.join(format(ord(i), 'b') for i in value)
print(binary('ab')) # prints all 14 characters
所以,如果你改為:
def binary(value):
return [format(ord(i), 'b') for i in value]
print(binary('ab'))
結果是:
['1100001', '1100010']
你可以和這樣的人一起作業:
bs = binary('ab')
print(bs[0])
print(bs[1])
print(''.join(bs))
結果:
1100001
1100010
11000011100010
例如,如果您只想在每個塊之間留一個空格:
print(' '.join(bs))
結果:
1100001 1100010
填充到 8 位字:
print(' '.join(b.zfill(8) for b in bs))
結果:
01100001 01100010
但是,要小心類似bs = binary('課題').
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/488820.html
