我有一个混合了字符和字节的列表,如下所示:
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?