Convert string serialized version of python bytes back to bytes

Question:

I have a byte string stored as a regular string.
For example: byte_str = "b’moose’"

Would like to convert this to a python bytes object. What is the best way? Thanks!

Asked By: greenberet123

||

Answers:

Use ast.literal_eval. For example:

from ast import literal_eval

byte_str = "b'moose'"
print(byte_str)
# "b'moose'"
actual_bytes = literal_eval(byte_str)
print(actual_bytes)
# b'moose'
Answered By: MattDMo
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.