What is the difference between __str__ and __repr__ in Python?

PythonServer Side ProgrammingProgramming

The built-in functions repr() and str() respectively call object.__repr__(self) and object.__str__(self) methods. First function computes official representation of the object, while second returns informal representation of the object.

Result of both functions is same for integer object.

>>> x = 1 
>>> repr(x)
'1'
>>> str(x)
'1'

However, it is not the case for string object.

>>> x = "Hello"
>>> repr(x)
"'Hello'"
>>> str(x)
'Hello'

Return value of repr() of a string object can be evaluated by eval() function and results in valid string object. However, result of str() can not be evaluated.

>>> y1 = repr(x)
>>> eval(y1)
'Hello'
>>> y2 = str(x)
>>> eval(y2)
NameError: name 'Hello' is not defined

To summarize. repr() returns a default and unambiguous representation of the object, where as str() gives an informal representation that may be readable but may not be always unambiguous.

raja
Published on 15-Jan-2018 00:10:13
Advertisements