The bytes data is stored as a string in a variable.
Eg: x = "\x61\x62\x63"
I need to convert this to its corresponding UTF-8. (In this case "abc").
I tried to convert it to bytes and then decode it, but the result was the input itself.
CodePudding user response:
>>> x = "\x61\x62\x63"
>>> x
'abc'
>>> bytes(x, 'utf-8')
b'abc'
>>> str(bytes(x, 'utf-8'))[2:-1]
'abc'
CodePudding user response:
Even though, I would not recommend to use eval
in production, you could do the following:
x = r"\x61\x62\x63"
code = 'b"{0}"'.format(x)
b = eval(code)
b.decode('utf-8')
Edit:
IIRC, the format string came with a later python version, so use
'b"{0}".format(x)'
.