user3479125 user3479125 - 15 days ago 6
Python Question

Reverse repr function in Python

if I have a string with characters (

0x61
0x62
0xD
), the
repr
function of this string will return
'ab\r'
.

Is there way to do reverse operation: if I have string
'ab\r'
(with characters
0x61
0x62
0x5C
0x72
), I need obtain string
0x61
0x62
0xD
.

Answer

I think what you're looking for is ast.literal_eval:

>>> s = repr("ab\r")
>>> s
"'ab\\r'"
>>> from ast import literal_eval
>>> literal_eval(s)
'ab\r'