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:
.__str__()
is intended to provide a nice or user-friendly string representation of an object.__repr__()
aims to provide a more precise and developer-friendly string representation that can often be used to recreate 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:
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.
Related Resources
Tutorial
When Should You Use .__repr__() vs .__str__() in Python?
In this tutorial, you'll learn the difference between the string representations returned by .__repr__() vs .__str__() and understand how to use them effectively in classes that you define.
For additional information on related topics, take a look at the following resources:
- Strings and Character Data in Python (Tutorial)
- Python's Magic Methods: Leverage Their Power in Your Classes (Tutorial)
- When to Use .__repr__() vs .__str__() in Python (Course)
- Using .__repr__() vs .__str__() in Python (Quiz)
- Strings and Character Data in Python (Course)
- Python Strings and Character Data (Quiz)
- Python's Magic Methods in Classes (Course)
- Python's Magic Methods: Leverage Their Power in Your Classes (Quiz)
By Leodanis Pozo Ramos • Updated June 3, 2025