Home > Net >  How to convert bytes to string only removing b"" in python 3
How to convert bytes to string only removing b"" in python 3

Time:09-30

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?

CodePudding user response:

I think what you are trying to achieve is you want to represent that back as a string without altering it:

data = b"\x80\x02\x03"
print(str(data)[2:-1])
The output is : \x80\x02\x03

CodePudding user response:

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

  • Related