简体   繁体   English

以二进制格式输出Python词典“值”

[英]Output Python Dictionary 'Values' as binary format

I have trying to solve this issue for a while. 我已经尝试解决这个问题了一段时间。 Have looked for simple answer but to no avail. 寻找简单的答案,但无济于事。 Any help much appreciated. 任何帮助,不胜感激。 I have created a python dictionary and am trying to format the output of the values only as binary data. 我创建了一个python字典,并试图将值的输出仅格式化为二进制数据。 In other words for each string value in the dictionary I want to output its binary value. 换句话说,对于字典中的每个字符串值,我要输出其二进制值。 My code and the error I am getting are below. 我的代码和我得到的错误如下。

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

You are asking ord to find a value based on 3 characters in a string. 您要ord查找基于字符串中3个字符的值。 More on the ord function here. 有关ord函数的更多信息,请参见此处。 In your for loop you are interacting over a list so your code expanded is like this. 在for循环中,您正在通过列表进行交互,因此扩展的代码如下所示。

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

Which would output, ABC, CDE, FGH . 将输出ABC, CDE, FGH To fix this either put another for loop on the actual string, or combine your original list into one string. 要解决此问题,请在实际字符串上放置另一个for循环,或将原始列表组合成一个字符串。

1) Another for loop. 1)另一个for循环。

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

2) Actual string. 2)实际字符串。

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

@Preston beat me to it with a better answer, but here is a solution that does not use nested list comprehension. @Preston用更好的答案击败了我,但这是不使用嵌套列表理解的解决方案。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM