- Trending Categories
- Data Structure
- Operating System
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Explain str() vs repr() functions in Python
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.
- str() vs repr() in Python?
- Python Alternate repr() implementation
- Explain Python vs Scala
- Macros vs Functions in C
- Functions vs Methods in Golang
- Explain Python regular expression search vs match
- Explain Inheritance vs Instantiation for Python classes.
- What does the repr() function do in Python Object Oriented Programming?
- How can I concatenate str and int objects in Python?
- What does the str() function do in Python Object Oriented Programming?