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 to string only removing b"" in python 3

I’m using python3 trying to convert bytes like b"\x80\x02\x03" to \x80\x02\x03
but using b"\x80\x02\x03".decode() gives a UnicodeDecodeError Exception

Does anyone know how to convert str obj to bytes obj without raising an error?

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 :

the problem is by default it tries to decode using utf8, which does not include all codepoints and sometimes has invalid multibyte messages

warning I’m pretty skeptical that the thing you are asking to do is actually what you want to do… generally if you have random bytes… you want random bytes as bytes not as a str

all that said perhaps you are looking for

b"\x80\x02\x03".decode('unicode-escape') 
# as pointed out in the comments this actually probably is NOT what you want

or maybe

# i **think** latin 1 has all codepoints 0-255...
b"\x80\x02\x03".decode('latin1') 

or if your title is literal and you just want to strip the b"

repr(b"\x80\x02\x03")[1:]

but that really probably isnt what you want to do

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