'How to extract list out from bytes class?

The values I want is extracted from the code response.content which returns the list of my values in bytes.

response.content = b'[11,22,33,44,55]'

I tried using a for loop to extract the values

example_bytes = b'[11,22,33,44,55]'
new_list = []
for i in example_bytes:
    print(i)

my i values returns a bunch of numbers which I don't understand. Could someone explain why is it like that? Is there a way to convert the bytes class to the list of just [11,22,33,44,55]?



Solution 1:[1]

This looks like a JSON response (check the response.headers["Content-Type"] to be sure), so use

response.json()

Or if you insist to decode the response.content manually:

json.loads(response.content)

Could someone explain why is it like that?

When you iterate a byte string you get the bytes as integers - ordinals of the "characters" themselves - for example the first number will be 91 and:

>>> ord('[')
91

The same is true for indexing a byte string, by the way:

>>> b'['[0]
91

Solution 2:[2]

They are the ascii values for the char in the bytes string.

I you convert the bytes string to regular string, then print the ascii values for each letter, it is much clearer:

# Bytes string
x = b'[11,22,33,44,55]'

for i in x.decode("utf-8"):
    print(ord(i))

This will return the same numbers as you get in your example


This will convert your response to a list:

# For string -> list
import ast

# Bytes string
x = b'[11,22,33,44,55]'

# Decode string, then convert to list
y = ast.literal_eval(x.decode("utf-8"))

But the other answer's suggestion of respose.json() is the correct way to convert this response. I suggest using their answer

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Freddy Mcloughlan