Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert bytes string to bytes

I have a string from a database request as follows:

result = "b'\x00\x00\x00\x00\x07\x80\x00\x03'"
type(result) -> <class 'str'>

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

a = b'\x00\x00\x00\x00\x07\x80\x00\x03'

type(a) -> <class 'bytes'>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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'\x00\x00\x00\x00\x07\x80\x00\x03'"
x = eval(a.encode("unicode-escape").decode())
print(type(x)) -> bytes

Same thing for the exec function.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading