Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse repr function in Python [duplicate]

Tags:

python

repr

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.

like image 848
Ivan Borshchov Avatar asked Jul 22 '14 11:07

Ivan Borshchov


People also ask

What does repr () do in Python?

The repr() function returns a printable representational string of the given object.

What is __ repr in Python?

Python __repr__() function returns the object representation in string format. This method is called when repr() function is invoked on the object. If possible, the string returned should be a valid Python expression that can be used to reconstruct the object again.

Is repr () a Python built-in function?

Definition. The Python repr() built-in function returns the printable representation of the specified object as a string. Python repr() function returns a printable representation of the object by converting that object to a string.

What is repr and str in Python?

Both str() and repr() return a “textual representation” of a Python object. The difference is: str() gives a user-friendly representation. repr() gives a developer-friendly representation.


1 Answers

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'
like image 158
jonrsharpe Avatar answered Oct 10 '22 07:10

jonrsharpe