22

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.

Ivan Borshchov
  • 3,036
  • 5
  • 40
  • 62
  • You can use [`hex`](https://docs.python.org/2/library/functions.html#hex) and [`ord`](https://docs.python.org/2/library/functions.html#ord), but `'\r'` isn't two characters. And `'\r'` is [`0xd`](http://www.fileformat.info/info/unicode/char/d/index.htm), not [`0x13`](http://www.fileformat.info/info/unicode/char/13/index.htm). – jonrsharpe Jul 22 '14 at 11:31
  • 1
    I use repr(that converts \r to two characters), becouse I need to see all special characters, and I need function, that are reverse to repr, becouse I need to enter the special characters in forman \ch. Yes, 0xD of course, sorry for mistake – Ivan Borshchov Jul 22 '14 at 11:37
  • it is not two characters if I write str="ab\r", but is when I read it from my GUI interface – Ivan Borshchov Jul 22 '14 at 11:40

1 Answers1

36

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'
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • Your code works, but not in my situation(( I need smth next: >>> s="ab\\r" >>> s 'ab\\r' >>> print(s) ab\r >>> literal_eval(s) Traceback (most recent call last): File "", line 1, in File "C:\Python27\lib\ast.py", line 49, in literal_eval node_or_string = parse(node_or_string, mode='eval') File "C:\Python27\lib\ast.py", line 37, in parse return compile(source, filename, mode, PyCF_ONLY_AST) File "", line 1 ab\r ^ SyntaxError: unexpected character after line continuation character – Ivan Borshchov Jul 22 '14 at 12:19
  • 1
    @user3479125 you don't have enough quotes - note that there are two pairs (one single, one double: `"'...'"`) in `s` in my example. Otherwise, `literal_eval` can't evaluate it as a string. – jonrsharpe Jul 22 '14 at 12:21
  • Why not just `eval`? – SeF Jul 13 '18 at 09:28
  • 1
    @SeF See here: [Using python's eval() vs. ast.literal_eval()](https://stackoverflow.com/q/15197673/10752293). – tedx May 21 '20 at 20:25