在 python 3 中,如何将字节对象中的单个字节放入列表中而不将它们转换为整数?



在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']

最新更新