Skip to content

String Representation: __str__ vs. __repr__

In Python, every object has a string representation. By default, custom objects look like a cryptic memory address: <__main__.Car object at 0x7f...>. To make your objects professional and easy to debug, you must override the “Magic Methods” responsible for string output.

The Python Data Model provides two distinct methods for this: __str__ and __repr__.


The __str__ method is meant to be informal and readable. Its primary goal is to provide a clear summary for an end-user.

  • Triggered by: print(obj), str(obj), and f-strings {obj}.
  • Goal: To be pretty.
str_demo.py
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __str__(self):
return f"'{self.title}' by {self.author}"
my_book = Book("1984", "George Orwell")
print(my_book) # Output: '1984' by George Orwell

The __repr__ (Representation) method is meant to be unambiguous and formal. Its primary goal is to provide enough information to recreate the object.

  • Triggered by: The interactive console, repr(obj), and inside collections (like lists).
  • Goal: To be precise.
repr_demo.py
class Book:
# ... __init__ ...
def __repr__(self):
return f"Book(title='{self.title}', author='{self.author}')"
# In a list, Python uses __repr__
library = [Book("1984", "Orwell"), Book("Dune", "Herbert")]
print(library)
# Output: [Book(title='1984', author='Orwell'), Book(title='Dune', author='Herbert')]

What happens if you only define one of them?

  • If you define only __repr__: Python uses it for both print() and the console.
  • If you define only __str__: Python uses it for print(), but the console/lists will still show the ugly <__main__...> address.

Best Practice: Always define __repr__ first. It’s the “fallback” that ensures your objects are always debuggable.


The distinction between these two comes from the philosophy that an object has an Identity (how the computer sees it) and a Value (how the human sees it).

  • __repr__ answers: “What is this object?”
  • __str__ answers: “What information does this object hold?”

When you use the REPL, Python calls repr() on every result to show you the “Raw” object. When you use print(), Python calls str() to give you a “Pretty” version.


Feature__str____repr__
Intended AudienceEnd UserDeveloper / Debugger
Output StyleInformal / PrettyFormal / Unambiguous
Default Fallbackobject.__repr__object.__repr__
Best PracticeOptional.Highly Recommended.