Reverse repr function in Python

Ivan Borshchov picture Ivan Borshchov · Jul 22, 2014 · Viewed 9.5k times · Source

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

jonrsharpe picture jonrsharpe · Jul 22, 2014

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'