在python 3中,我有一个长度大于1的bytes
对象。我想将单个字节放入list
下面是一个示例:
myBytes = b'abc123' # should turn into [b'a', b'b', b'c', b'1', b'2', b'3']
我尝试了以下方法:
badList0 = []
badList0.extend(myBytes) # badList0 = [97, 98, 99, 49, 50, 51]
badList1 = []
badList1.extend(bytearray(myBytes)) # badList1 = [97, 98, 99, 49, 50, 51]
badList2 = list(myBytes) # badList2 = [97, 98, 99, 49, 50, 51]
badList3 = [bytes(b) for b in myBytes] # result is 6 entries with 97, 98, 99, 49, 50, and 51 'x00's, respectively
有没有一种清晰有效的方法来获得单个bytes
对象列表([b'a', b'b', b'c', b'1', b'2', b'3']
(的所需结果,而不是代表这些字节的整数值列表?
这是丑陋的方式:
[bytes([c]) for c in bs]
不知道是否有更漂亮的东西。
解码为utf-8
并编码回字节数组:
list(map(str.encode, myBytes.decode("utf-8")))
# [b'a', b'b', b'c', b'1', b'2', b'3']
我用过:[bytes([myBytes[i]]) for i in range(len(myBytes))]
并得到输出:[b'a', b'b', b'c', b'1', b'2', b'3']
这是一种方法:
[bytes(i, 'utf-8') for i in myBytes.decode('utf-8')]
# [b'a', b'b', b'c', b'1', b'2', b'3']