Explain str() vs repr() functions in Python

PythonServer Side ProgrammingProgramming

The official Python documentation says __repr__ is used to find the “official” string representation of an object and __str__ is used to find the “informal” string representation of an object. The print statement and str() built-in function uses __str__ to display the string representation of the object while the repr() built-in function uses __repr__ to display the object. Let us take an example to understand what the two methods actually do.

Let us create a datetime object −

>>> import datetime
>>> today = datetime.datetime.now()
When I use the built-in function str() to display today:
>>> str(today)
'2018-01-12 09:21:58.130922'

We see that the date was displayed as a string in such a way that the user can understand the date and time. Now lets see when we use the built-in function repr()−

>>> repr(today)
'datetime.datetime(2018, 1, 12, 9, 21, 58, 130922)'

We see that this also returned a string but the string was the “official” representation of a datetime object which means that this “official” string representation can reconstruct the object −

>>> eval('datetime.datetime(2018, 1, 12, 9, 21, 58, 130922)')
datetime.datetime(2018, 1, 12, 9, 21, 58, 130922)

The eval() built-in function accepts a string and converts it to a datetime object.

Thus in a general every class we code must have a __repr__ and if you think it would be useful to have a string version of the object, as in the case of datetime create a __str__ function.

raja
Published on 18-Jan-2018 12:18:39
Advertisements