string representation

In Python, string representation refers to how objects are represented as strings. This feature is essential for debugging and logging purposes.

Python offers two primary special methods for defining string representations:

  1. .__str__() is intended to provide a user-friendly string representation of an object.
  2. .__repr__() aims to provide a more precise and developer-friendly string representation that can often be used to re-create the object.

When you print an object or use the built-in str() function, Python internally calls the .__str__() method. If .__str__() isn’t defined, then Python falls back to .__repr__(). Conversely, if you use the built-in repr() function or access the object in a REPL, Python calls .__repr__().

Example

Here’s an example that illustrates both string representations:

Python cars.py
class Car:
    def __init__(self, make, model):
        self.make = make
        self.model = model

    def __str__(self):
        return f"{self.make} {self.model}"

    def __repr__(self):
        cls = type(self).__name__
        return f"{cls}(make='{self.make}', model='{self.model}')"

# Usage
corolla = Car("Toyota", "Corolla")
print(str(corolla))  # Output: Toyota Corolla
print(repr(corolla)) # Output: Car(make='Toyota', model='Corolla')

In this example, .__str__() provides a user-friendly description of the concrete Car object, while .__repr__() gives a developer-friendly representation suitable for debugging.

Tutorial

When Should You Use .__repr__() vs .__str__() in Python?

Find out when to choose Python's __repr__() vs __str__() in your classes so your objects show helpful information for debugging and user output.

intermediate best-practices

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Oct. 15, 2025