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!
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'
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!
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'