0

I have a string like this "b'\\x00\\x01\\x02\\x03\\x04'" which represents bytes, and I want to convert it into actual bytes.

I've tried doing this:

string = "b'\\x00\\x01\\x02\\x03\\x04'"

data = bytes(string[2:-1], "utf-8") # Removing quotes and the b
print(data, type(data))

>>> b'\\x00\\x01\\x02\\x03\\x04' <class 'bytes'>

But the data bytes have double slashes.


Note:
It works using eval but for security reasons I won't use it.

Patitotective
  • 35
  • 1
  • 7

1 Answers1

1

Use ast.literal_eval:

Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, None and Ellipsis. This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself.

import ast

string = "b'\\x00\\x01\\x02\\x03\\x04'"

data = ast.literal_eval(string)
Pedro Maia
  • 2,666
  • 1
  • 5
  • 20