Python str() vs repr(): What Is the Difference?
str() returns a readable version of an object meant for users, while repr() returns an unambiguous version meant for developers, which for strings includes the quotes.For numbers the two functions look the same, which hides the difference. With strings, containers and your own classes the gap is clear: str("hi") gives hi but repr("hi") gives 'hi'. Python uses str() when you print() an object or format it in an f-string, and repr() when it shows an object in the interactive shell, inside a list, or in a debugger.
The str() function page covers conversion in detail. Here we focus on how it differs from repr() and how to implement both on your own classes, which builds on Python dunder methods.
str() vs repr() compared
| Aspect | `str(obj)` | `repr(obj)` |
|---|---|---|
| Audience | End users | Developers |
| Goal | Readable | Unambiguous, ideally valid Python code |
| Special method | __str__ | __repr__ |
Result for "hi" | hi | 'hi' |
Used by print() | Yes | Only if __str__ is missing |
| Used inside lists and dicts | No | Yes: containers show repr() of items |
| Falls back to the other? | Uses __repr__ if __str__ is missing | Never falls back to __str__ |
When to use str()
Use str() (or just print() and f-strings, which call it for you) when the text is for the person using your program: messages, reports and labels. It aims for a friendly form such as Asha (age 20), not for exactness.
When to use repr()
Use repr() when you debug, log or want to see exactly what a value is. It reveals hidden details, like quotes around strings, \n escapes and the difference between 5 and "5". The !r conversion in an f-string, as in f"{name!r}", calls it for you. A good __repr__ looks like the code that would rebuild the object, such as Student('Asha', 20).
label = "line1\nline2"
print(label)
print(repr(label))How to define __str__ and __repr__ in a class
Always write __repr__ first. If you define only __repr__, Python reuses it for str() and print(), so you still get useful output. Add __str__ only when you want a friendlier user-facing text. Both methods must return a string; printing inside them returns None and raises TypeError. See classes and objects for the basics of defining methods.
Examples you can run
Press Run, then edit the code and run it again.
Strings show quotes only in repr()
The same value gives two different texts; the quotes in the repr() result tell you it is a string.
name = "Asha"
print(str(name))
print(repr(name))
print(str(42), repr(42))Expected outputAsha
'Asha'
42 42
Containers use repr() for their items
print() of a list calls str() on the list, but the list builds its text from repr() of each item.
names = ["Asha", "Ravi"]
print(names)
print("Asha", "Ravi")
print(f"{names[0]!r}")Expected output['Asha', 'Ravi']
Asha Ravi
'Asha'
A class with both __repr__ and __str__
print() uses __str__, while the list display and repr() use __repr__.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Student({self.name!r}, {self.age})"
def __str__(self):
return f"{self.name} (age {self.age})"
s = Student("Asha", 20)
print(s)
print(repr(s))
print([s])Expected outputAsha (age 20)
Student('Asha', 20)
[Student('Asha', 20)]
Only __repr__ defined: print() reuses it
With no __str__, str() falls back to __repr__.
class Item:
def __repr__(self):
return "Item(pen)"
print(Item())
print(str(Item()))Expected outputItem(pen)
Item(pen)
Common mistakes
Returning None from __str__ because of print()
✗ Wrong
class Item:
def __str__(self):
print("pen")
print(Item())✓ Right
class Item:
def __str__(self):
return "pen"
print(Item())__str__ and __repr__ must return a string; do not print inside them.
Defining only __str__ and expecting it in lists
✗ Wrong
class Item:
def __str__(self):
return "pen"
print(len(repr(Item())) > 10)✓ Right
class Item:
def __repr__(self):
return "Item('pen')"
print([Item()])Define __repr__ as well, or instead of __str__.
Parsing repr() output as a stable format
✗ Wrong
text = repr(3.0)
print(text + 1)✓ Right
text = repr(3.0)
print(float(text) + 1)Both functions return strings. Convert back with float() or int(), and use json for real data exchange rather than relying on repr().
Python str() vs repr(): What Is the Difference?: questions people ask
What is the difference between __str__ and __repr__ in Python?
__str__ returns a readable string for users and is used by print() and str(), while __repr__ returns an unambiguous string for developers and is used by repr(), the shell and containers. If only __repr__ exists, Python uses it for both.
Which should I implement first, __str__ or __repr__?
Implement __repr__ first. It gives you debugging output everywhere and also serves as the fallback for str(). Add __str__ later only if you want a different, friendlier display.
Why does print(list) show quotes around strings?
Because a list displays each item with repr(), and the repr() of a string includes its quotes. Printing the strings individually uses str(), so no quotes appear.
Keep learning
Step-by-step lessons:
Python Dunder (Magic) MethodsPython StringsPython Classes and Objects
Related:
Python str() FunctionPython print() FunctionPython f-StringsPython type() Function
More in functions and methods:
Python append() vs extend(): What Is the Difference?Python sort() vs sorted(): What Is the Difference?Python remove() vs pop() vs del: What Is the Difference?Python print() vs return: What Is the Difference?Python Deep Copy vs Shallow Copy: What Is the Difference? See all →