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

Question:

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

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

Asked By: Lawrence Williams

||

Answers:

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"x80x02x03".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"x80x02x03".decode('latin1') 

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

repr(b"x80x02x03")[1:]

but that really probably isnt what you want to do

Answered By: Joran Beasley

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

data = b"x80x02x03"
print(str(data)[2:-1])
The output is : x80x02x03
Answered By: Claudiu T
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.