str() and repr() both are used to get a string representation of object.
- Example of str():
Hello, Geeks. 0.181818181818
- Example of repr():
'Hello, Geeks.' 0.18181818181818182
From above output, we can see if we print string using repr() function then it prints with a pair of quotes and if we calculate a value we get more precise value than str() function.
Following are differences:
- str() is used for creating output for end user while repr() is mainly used for debugging and development. repr’s goal is to be unambiguous and str’s is to be readable. For example, if we suspect a float has a small rounding error, repr will show us while str may not.
- repr() compute the “official” string representation of an object (a representation that has all information about the object) and str() is used to compute the “informal” string representation of an object (a representation that is useful for printing the 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 understand this by an example:-
2016-02-22 19:32:04.078030 datetime.datetime(2016, 2, 22, 19, 32, 4, 78030)
str() displays today’s date in a way that the user can understand the date and time.
repr() prints “official” representation of a date-time object (means using the “official” string representation we can reconstruct the object).
How to make them work for our own defined classes?
A user defined class should also have a __repr__ if we need detailed information 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 is contributed by Arpit Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Python - Read blob object in python using wand library
- Important differences between Python 2.x and Python 3.x with examples
- Python | Index of Non-Zero elements in Python list
- Python | Merge Python key values to list
- Python | Convert list to Python array
- Reading Python File-Like Objects from C | Python
- Python | PRAW - Python Reddit API Wrapper
- MySQL-Connector-Python module in Python
- twitter-text-python (ttp) module - Python
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Sort Python Dictionaries by Key or Value
- Python | Add Logging to Python Libraries
- Python | Add Logging to a Python Script
- Python | Visualizing O(n) using Python
- Python | a += b is not always a = a + b
- set add() in python
- SQL using Python | Set 1
- Python Set | pop()
- SHA in Python
Improved By : rajivsarkar67