Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the difference between __str__ and __repr__ in Python?
The __str__ and __repr__ methods in Python serve different purposes for string representation of objects. The __str__ method provides a human-readable representation, while __repr__ provides an unambiguous, developer-friendly representation that ideally can recreate the object.
Key Differences
The built-in functions str() and repr() call the __str__() and __repr__() methods respectively. The repr() function computes the official representation of an object, while str() returns the informal representation.
| Method | Purpose | Target Audience | Should be Evaluable? |
|---|---|---|---|
__str__ |
Human-readable | End users | No |
__repr__ |
Unambiguous | Developers | Ideally yes |
Example with Integer Objects
For simple objects like integers, both methods return the same result ?
x = 1
print("repr(x):", repr(x))
print("str(x):", str(x))
repr(x): 1 str(x): 1
Example with String Objects
For string objects, the difference becomes clear ?
x = "Hello"
print("repr(x):", repr(x))
print("str(x):", str(x))
repr(x): 'Hello' str(x): Hello
Evaluating with eval()
The repr() result can be evaluated with eval() to recreate the object, while str() cannot ?
x = "Hello"
y1 = repr(x)
print("repr result:", y1)
print("eval(repr):", eval(y1))
y2 = str(x)
print("str result:", y2)
# This would cause NameError
try:
eval(y2)
except NameError as e:
print("eval(str) error:", e)
repr result: 'Hello' eval(repr): Hello str result: Hello eval(str) error: name 'Hello' is not defined
Custom Class Example
Here's how to implement both methods in a custom class ?
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}, {self.age} years old"
def __repr__(self):
return f"Person('{self.name}', {self.age})"
person = Person("Alice", 30)
print("str():", str(person))
print("repr():", repr(person))
str(): Alice, 30 years old
repr(): Person('Alice', 30)
Conclusion
Use __repr__ for unambiguous, developer-friendly output that can ideally recreate the object. Use __str__ for readable, user-friendly display. When only one is defined, Python uses __repr__ as a fallback for str().
