Difference Between str() and repr() in Python
In Python, both str() and repr() convert
objects into string representations, but they serve two distinct
audiences and purposes. The primary difference is that
str() produces an informal, human-readable output intended
for end users, while repr() generates a formal, unambiguous
representation designed for developers and debugging. When designing
classes, implementing both methods properly ensures that your objects
are easy to display in user interfaces and straightforward to inspect
during development.
Purpose and Audience
The goal of str() is readability. It formats an object
into a clean, intuitive string suitable for display in terminal outputs,
logs, or user-facing text. It is automatically called by the built-in
print() and format() functions.
The goal of repr() is precision and unambiguity. It
reveals the underlying data types and structures, often formatted so
that passing the result to eval() recreates the original
object (though this is not an absolute rule). The Python interactive
shell uses repr() to display values.
A Concrete Example: Strings and Dates
The distinction is most noticeable with built-in types such as
strings and datetime objects:
import datetime
today = datetime.datetime.now()
# str() focuses on clean presentation
print(str(today))
# Output: 2024-05-17 14:30:00.123456
# repr() provides the exact representation for developers
print(repr(today))
# Output: datetime.datetime(2024, 5, 17, 14, 30, 0, 123456)With plain strings, str() drops the enclosing quotes,
whereas repr() retains quotes and explicitly displays
escape characters:
text = "Hello\nWorld"
print(str(text))
# Output:
# Hello
# World
print(repr(text))
# Output: 'Hello\nWorld'Fallback Behavior in Python Classes
When creating custom classes, Python looks for the special methods
__str__() and __repr__():
- If you call
repr(obj), Python looks exclusively for__repr__(). - If you call
str(obj), Python looks for__str__(). If__str__()is not defined, it falls back to__repr__(). - If neither is explicitly defined, Python falls back to the default
implementation inherited from
object, which prints the object's class name and memory address (e.g.,<__main__.Car object at 0x1045...>).
Because of this fallback mechanism, the best practice is to always
define __repr__() first to ensure useful debugging
information, and then define __str__() only if a more
user-friendly representation is required.
Custom Class Implementation
Here is how both methods are typically implemented together:
class User:
def __init__(self, username, user_id):
self.username = username
self.user_id = user_id
def __str__(self):
# User-friendly string
return f"User: {self.username}"
def __repr__(self):
# Unambiguous, code-like string
return f"User(username='{self.username}', user_id={self.user_id})"
user = User("alice", 42)
print(str(user)) # Output: User: alice
print(repr(user)) # Output: User(username='alice', user_id=42)Summary of Differences
| Feature | str() |
repr() |
|---|---|---|
| Primary Audience | End users | Developers / Debuggers |
| Goal | Readability | Unambiguity and precision |
| Underlying Method | __str__() |
__repr__() |
| Fallback | Calls __repr__() if
__str__() is absent |
Default object
implementation |
| Interactive Shell | Used when calling print()
explicitly |
Used automatically by the REPL |