Python __str__ Method
Last modified November 18, 2026 Python 3.15
The __str__ method returns the human-readable representation of an
object. Python calls it from print(), str() and plain
f-strings. Unlike __repr__, which aims to be unambiguous for
developers, __str__ should be pleasant for an end user to read.
This article shows the basic method, the fallback to __repr__, the
difference between the two, formatted output, inheritance, state-dependent
content and what happens when the method returns a non-string.
A basic __str__
The method returns a string. Both print(obj) and
str(obj) call it, so a single implementation covers the common
display paths.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"Person: {self.name}, {self.age} years old"
p = Person("Alice", 30)
print(p)
print(str(p))
Both calls produced the same readable text. The method did the printing itself nowhere — it returned a string, and the two callers displayed it.
$ python basic_str.py Person: Alice, 30 years old Person: Alice, 30 years old
Falling back to __repr__
When a class defines only __repr__, Python uses it for
str() too. This is why writing one good representation is often
enough for a small debugging helper.
class Marker:
def __repr__(self):
return "Marker()"
m = Marker()
print("str:", str(m))
print("repr:", repr(m))
print("default object:", object().__repr__()[:9])
Both calls returned Marker(). The default representation from
object is the familiar angle-bracket form containing a memory
address, which is why defining at least one of the two methods is useful.
$ python fallback.py str: Marker() repr: Marker() default object: <object o
__str__ versus __repr__
The two methods serve different audiences. The example prints a point four ways so the difference in each context is visible, including the two f-string conversions.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Point({self.x}, {self.y})"
def __str__(self):
return f"({self.x}, {self.y})"
p = Point(3, 4)
print("str: ", str(p))
print("repr: ", repr(p))
print("f-string: ", f"{p}")
print("f-string with !r", f"{p!r}")
A plain f-string uses __format__, which falls back to
__str__. Adding !r forces the representation path
instead. The repr includes the class name, which makes it more
useful in logs.
$ python str_vs_repr.py str: (3, 4) repr: Point(3, 4) f-string: (3, 4) f-string with !r Point(3, 4)
Formatted output
A representation can use the string formatting mini-language to align columns. The result is still one string, returned to the caller.
class Product:
def __init__(self, name, price, quantity):
self.name = name
self.price = price
self.quantity = quantity
def __str__(self):
header = f"{'Name':<15}{'Price':>10}{'Quantity':>12}"
divider = "-" * 37
row = f"{self.name:<15}${self.price:>9.2f}{self.quantity:>12}"
return f"{header}\n{divider}\n{row}"
print(Product("Laptop", 1299.99, 5))
The left-aligned name and right-aligned price and quantity line up into a
small table. Building the string in __str__ lets the caller print
the object without knowing its internal layout.
$ python formatting.py Name Price Quantity ------------------------------------- Laptop $ 1299.99 5
Inheritance
A subclass can extend the parent's string by calling
super().__str__() and appending its own fields. This keeps the
formatting rule for the shared part in one place.
class Animal:
def __init__(self, species):
self.species = species
def __str__(self):
return f"Species: {self.species}"
class Dog(Animal):
def __init__(self, name, breed):
super().__init__("Canine")
self.name = name
self.breed = breed
def __str__(self):
parent = super().__str__()
return f"{parent}, Name: {self.name}, Breed: {self.breed}"
print(Dog("Buddy", "Golden Retriever"))
The parent supplied the species portion and the child added name and breed.
Chaining with super() means a change to the parent format is
picked up automatically.
$ python inheritance.py Species: Canine, Name: Buddy, Breed: Golden Retriever
State-dependent content
Because the method reads the object's current state, the text changes as that state changes. This progress bar computes both the filled portion and the percentage each time it is displayed, so the output is deterministic and easy to test.
class ProgressBar:
def __init__(self, done, total):
self.done = done
self.total = total
def __str__(self):
percent = 100 * self.done / self.total
return f"[{'#' * self.done}{'.' * (self.total - self.done)}] {percent:.0f}%"
bar = ProgressBar(6, 10)
print(bar)
bar.done = 10
print(bar)
The second call reflected the updated done value. The older
version of this article used the current clock hour to pick a greeting, which
made the output depend on when the example happened to run.
$ python progress.py [######....] 60% [##########] 100%
Returning a non-string
Python enforces the contract at runtime: the method must return a
str. Returning another type produces a
TypeError.
class Broken:
def __str__(self):
return 42
try:
str(Broken())
except TypeError as e:
print(type(e).__name__, e)
The error names both the class and the offending type. If you need to show a
number, convert it with str() or an f-string before returning.
$ python wrong_type.py TypeError Broken.__str__() must return a str, not int
Best practices
A few rules keep __str__ useful:
- Return a readable string that highlights the most important state.
- Define
__repr__as well when the object appears in logs or collections. - Remember that plain f-strings use
__str__and!ruses__repr__. - Call
super().__str__()when extending an existing representation. - Do not print inside the method — return the string and let the caller decide what to do with it.
Source
object.__str__ - Python documentation
Format string syntax - Python documentation
In this article we have implemented the __str__ method. We have
covered the basic representation, the fallback to __repr__, the
difference between the two, formatted output, inheritance, dynamic content and
the string return requirement. For related topics, see
Python __repr__ method,
Python __format__ method, and
Python f-strings.
Author
List all Python tutorials.