2016-11-10 53 views
2

我試圖解決這個問題一段時間。已經找到了簡單的答案,但無濟於事。任何幫助非常感謝。我創建了一個python字典,並試圖將值的輸出格式化爲只有二進制數據。換句話說,對於字典中的每個字符串值,我想輸出它的二進制值。我的代碼和我得到的錯誤如下。輸出Python字典'值'爲二進制格式

pigpen = {} 
pigpen['a'] = 'ETL' 
pigpen['b'] = 'ETM' 
pigpen['c'] = 'ETR' 
pigpen['d'] = 'EML' 
pigpen['e'] = 'EMM' 
pigpen['f'] = 'EMR' 
pigpen['g'] = 'EBL' 
pigpen['h'] = 'EBM' 
pigpen['i'] = 'EBR' 
pigpen['j'] = 'DTL' 
pigpen['k'] = 'DTM' 
pigpen['l'] = 'DTR' 
pigpen['m'] = 'DML' 
pigpen['n'] = 'DMM' 
pigpen['o'] = 'DMR' 
pigpen['p'] = 'DBL' 
pigpen['q'] = 'DBM' 
pigpen['r'] = 'DBR' 
pigpen['s'] = 'EXT' 
pigpen['t'] = 'EXL' 
pigpen['u'] = 'EXR' 
pigpen['v'] = 'EXB' 
pigpen['w'] = 'DXT' 
pigpen['x'] = 'DXL' 
pigpen['y'] = 'DXR' 
pigpen['z'] = 'DXB' 

import binascii 
str = pigpen.values() 
print ' '.join(format(ord(string), 'b') for string in str) 

Traceback (most recent call last): 
    File "pigpen_build.py", line 62, in <module> 
    print ' '.join(format(ord(string), 'b') for string in str) 
    File "pigpen_build.py", line 62, in <genexpr> 
    print ' '.join(format(ord(string), 'b') for string in str) 
TypeError: ord() expected a character, but string of length 3 found 
>>> 
+0

你是什麼意思的二進制值?你能提供一個示例輸出嗎? – amirouche

+0

二進制值是該角色的ascii值。看看python的'ord'和'chr'函數。 –

+0

非常感謝幫助傢伙。 – Dac121

回答

0

您要求ord根據字符串中的3個字符查找值。更多關於the ord function here.在for循環中,您正在通過列表進行交互,以便您的代碼擴展爲這樣。

for s in ['ABC','CDE','FGH']: 
    print s+', ', 

將輸出,ABC, CDE, FGH。要解決此問題,請將另一個for循環放在實際字符串上,或者將您的原始列表合併爲一個字符串。

1)另一個for循環。

print ' '.join(format(ord(string), 'b') for string in (''.join(s for s in str))) 

2)實際字符串。

str = ''.join(s for s in str) 
print ' '.join(format(ord(stirng), 'b') for string in str) 
+0

非常感謝幫助傢伙。 – Dac121

0

@Preston用更好的答案打敗了我,但是這裏有一個解決方案,它不使用嵌套列表理解。

binary_translation = [] 
for string in a: 
    for char in string: 
     binary_translation.append(''.join(format(ord(char), 'b'))) 
+0

非常感謝幫助傢伙。 – Dac121