Reverse repr function in Python [duplicate]
Asked Answered
P

1

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.

Pallua answered 22/7, 2014 at 11:26 Comment(3)
You can use hex and ord, but '\r' isn't two characters. And '\r' is 0xd, not 0x13.Darciedarcy
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 mistakePallua
it is not two characters if I write str="ab\r", but is when I read it from my GUI interfacePallua
D
37

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'
Darciedarcy answered 22/7, 2014 at 11:40 Comment(4)
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 "<stdin>", line 1, in <module> 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 "<unknown>", line 1 ab\r ^ SyntaxError: unexpected character after line continuation characterPallua
@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.Darciedarcy
Why not just eval?Imperceptible
@Imperceptible See here: Using python's eval() vs. ast.literal_eval().Amado

© 2022 - 2024 — McMap. All rights reserved.