What is the difference between Python's `str()` and `repr()`?

In Python, `str()` and `repr()` are both functions used to represent an object as a string, but they serve slightly different purposes:

1. `str()`: This function is used to create a human-readable string representation of an object. When you call `str()` on an object, it tries to return a user-friendly representation of the object. It is typically used for creating output for end-users or when you want to display information about the object in a readable format.

2. `repr()`: This function is used to create an unambiguous string representation of an object. When you call `repr()` on an object, it returns a string that could be used to recreate the object. It is typically used for debugging and logging purposes or when you need a more precise representation of the object.

Here is an example to illustrate the difference between `str()` and `repr()`:



import datetime

now = datetime.datetime.now()

print(str(now)) # Output: 2022-01-01 12:00:00
print(repr(now)) # Output: datetime.datetime(2022, 1, 1, 12, 0)



In the example above, `str(now)` provides a human-readable representation of the `datetime` object, while `repr(now)` gives a more detailed and unambiguous representation of the object.

In summary, `str()` is used for creating readable output for end-users, while `repr()` is used for creating unambiguous representations for developers.
What is the difference between Python's `str()` and `repr()`?

Related Questions