'How to convert a string representation of 'bytes' to its corresponding 'utf-8' in Python? (Python 3.7)
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.
Solution 1:[1]
>>> x = "\x61\x62\x63"
>>> x
'abc'
>>> bytes(x, 'utf-8')
b'abc'
>>> str(bytes(x, 'utf-8'))[2:-1]
'abc'
Solution 2:[2]
Even though, I would not recommend to use eval in production, you could do the following:
import ast
x = r"\x61\x62\x63"
code = 'b"{0}"'.format(x)
b = ast.literal_eval(code)
b.decode('utf-8')
Edit:
IIRC, the format string came with a later python version, so use
'b"{0}".format(x)'.
Edit: Added comment by Mark Tolonen.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | AlarmClockMan |
| Solution 2 |
