如何将字符和字节列表转换为纯字节列表?

时间:2013-10-08 18:03:22

标签: python list

我有一个字符和字节混合的列表,如下所示:

myData = ['a', '\x65', 'B', '\x66\x69', 'C']

我想将此列表转换为字节数组,所以:

myByteArray = ['\x61' , '\x65', '\x42', '\x66', '\x69', '\x43']

到目前为止我尝试过的是myData上的简单显示 -

myData = ['a', '\x65', 'B', '\x66\x69', 'C']
print " ".join(hex(ord(n)) for n in myData)

由于数组中的元素恰好是两个字节,因此会抛出此错误:

Traceback (most recent call last):
  File "./test.py", line 3, in <module>
    print " ".join(hex(ord(n)) for n in myData)
  File "./test.py", line 3, in <genexpr>
    print " ".join(hex(ord(n)) for n in myData)
TypeError: ord() expected a character, but string of length 2 found

如何将原始列表myData转换为字节数组myByteArray?

2 个答案:

答案 0 :(得分:1)

您可以将它们全部合并,然后再次拆分以获取各个字符,例如:

   output_list = [hex(ord(c)) for c in ''.join(myData)]

尝试一下,

>>> myData = ['a', '\x65', 'B', '\x66\x69', 'C']
>>> [hex(ord(c)) for c in ''.join(myData)]
['0x61', '0x65', '0x42', '0x66', '0x69', '0x43']

答案 1 :(得分:1)

如果你真的想要一个list可变字节而不是一个不可变的单字符字符串,你可以这样做:

myData = ['a', '\x65', 'B', '\x66\x69', 'C', '\xff']

myByteArray = bytearray(''.join(myData))

print " ".join(hex(byte) for byte in myByteArray)
# 0x61 0x65 0x42 0x66 0x69 0x43 0xff

如果一个字符的list字符串没问题,那么您只需要:

myByteArray = list(''.join(myData))