tintedFrantic
tintedFrantic

Reputation: 187

In python 3, how can I put individual bytes from a bytes object into a list without them being converted to integers?

In python 3, I have a bytes object that has length greater than 1. I would like to put the individual bytes into a list Here is an example:

myBytes = b'abc123'  # should turn into [b'a', b'b', b'c', b'1', b'2', b'3']

I have tried the following:

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

Is there a clear and efficient way to get the desired result of a list of individual bytes objects ([b'a', b'b', b'c', b'1', b'2', b'3']) instead of a list of integer values representing those bytes?

Upvotes: 3

Views: 399

Answers (4)

r.ook
r.ook

Reputation: 13888

Here's one way:

[bytes(i, 'utf-8') for i in myBytes.decode('utf-8')]

# [b'a', b'b', b'c', b'1', b'2', b'3']

Upvotes: 1

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 96171

Here's the ugly way:

[bytes([c]) for c in bs]

Not sure if there's something much prettier.

Upvotes: 3

meph
meph

Reputation: 692

I used:
[bytes([myBytes[i]]) for i in range(len(myBytes))]
And got the output:
[b'a', b'b', b'c', b'1', b'2', b'3']

Upvotes: 1

yatu
yatu

Reputation: 88275

Decode to utf-8 and encode back to a bytearray:

list(map(str.encode, myBytes.decode("utf-8")))
# [b'a', b'b', b'c', b'1', b'2', b'3']

Upvotes: 2

Related Questions