str () and repr () are both used to get a string representation of an object.
Hello, Geeks. 0.181818181818
'Hello, Geeks.' 0.18181818181818182
Based on the above output, we can see that if we print a string using the repr () function, it prints with a couple of quotes, and if we evaluate the value, we get a more accurate value than the str () function.
Below are the differences: p>
Let's understand this with an example: —
2016-02-22 19:32 : 04.078030 datetime.datetime (2016, 2, 22, 19, 32, 4, 78030)
str () displays today's date so that the user can understand the date and time.
repr () prints the "official" representation of the date and time object (hence, using the "official" string (we can reverse engineer the object).
How do we make them work for our own defined classes?
The custom class must also have __repr__ if we want details for debugging. And if we think it would be useful to have a string version for users, we create a __str__ function.
10 + i20 Rational (10, 20)
This article courtesy of Arpit Agarwal. If you like Python.Engineering and would like to contribute your contribution, you can also write an article and mail it to [email protected] See your article appearing on the Python.Engineering homepage and help other geeks.
Please post comments if you find anything wrong or would like to share more information on the topic under discussion