Convert bytes into list

Question:

I am new to this sort of stuff, so sorry if it’s really simple and I am just being stupid.

So I have this variable with some bytes in it (not sure if that’s the right name.)
data = b’redx00XYx001x00168.93×00859.07×00′

I need to convert this to a list. The intended output would be something like.
[“red”,”XY”,”1″,”169.93″,”859.07″]

How would I go about doing this?

Thank you for your help.

Asked By: WimpyLlama

||

Answers:

We can use the following line:

[x.decode("utf8") for x in data.split(b"x00") if len(x)]

Going part by part:

  • x.decode("utf8"): x will be a bytes string, so we need to convert it into a string via `.decode(“utf8”).
  • for x in data.split(b"x00"): We can use python’s built in bytes.split method in order to split the byte string by the nullbytes to get an array of individual strings.
  • if len(x): This is equivalent to if len(x) > 0, since we want to discard the empty string at the end.
Answered By: Aplet123

This code may help you to understand if you want exact same output using the pop() function.

data = 'red/x00XY/x001/x00168.93/x00859.07/x00'  # I change "/" mark from "" because i'm  using Linux otherwise it will give error in Linux
 
new_list = []  # There is a variable that contain empty list

for item in data.split('/x00'):  # Here I use split function by default it splits variable where "," appears but in this case
    new_list.append(item)        # you need list should be separated by "/" so that's why I gave split('/x00') and one by list appended
    
print(new_list)

Answered By: Muhammad Anas Atiq
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.