How to convert bytes string to bytes


I have a string from a database request as follows:

result = "b'x00x00x00x00x07x80x00x03'"
type(result) -> <class 'str'>

How do I convert it to bytes? It should be like this:

a = b'x00x00x00x00x07x80x00x03'

type(a) -> <class 'bytes'>
Asked By: Corvych



From what I understood (I have a terrible understanding of english):
You can use the eval() or the exec() function to convert a string to any Python object you want.
Here’s an example:

a = "b'x00x00x00x00x07x80x00x03'"
x = eval(a.encode("unicode-escape").decode())
print(type(x)) -> bytes

Same thing for the exec function.

Answered By: greenegran0

You shouldn’t use eval() function unless you truth the input like greenegran0 answer, because it can make your code insecure.

You can use bytes() class or encode() function to convert it into bytes instead.

result = "b'x00x00x00x00x07x80x00x03'"
result = bytes(result[2:-1], "latin1") # result[2:-1] remove b'' at the beginning and end
#Or: result = result[2:-1].encode("latin1")

print(type(result)) # Return <class 'bytes'>
Answered By: YoutuberTom
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.