What is the difference between __str__ and __repr__ in Python?



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.

Updated on: 2019-07-30T22:30:21+05:30

241 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements