How to convert bytes string to bytes
Question:
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'>
Answers:
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.
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'>
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'>
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.
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'>