__str__
__str__(self) str · Added in vPython 1.0 · Updated March 18, 2026 · Keywords __str__
Python’s __str__ method lets you define a human-readable string representation for your objects. It’s what controls what users see when they print an object or convert it to a string.
Overview
__str__ is a special method that returns a human-readable string representation of an object. Unlike the technical representation you’d use for debugging, __str__ is designed for end users—simple and readable.
Python calls __str__ automatically when you use:
print(obj)str(obj)- f-strings like
f"{obj}" format()function
Syntax
def __str__(self):
# Return a string
return "your description here"
Key points:
- Takes only
self—no other parameters - Must return a string, not print it
- If you forget to return, Python raises
TypeError: __str__ returned non-string (type NoneType)
How It Works
When you create a class without __str__, Python shows something unhelpful like <__main__.Person object at 0x...>. Define __str__ and you control exactly what users see.
class Person:
def __init__(self, name, role):
self.name = name
self.role = role
def __str__(self):
return f"{self.name} ({self.role})"
user = Person("Alice", "Engineer")
print(user) # Alice (Engineer)
print(str(user)) # Alice (Engineer)
Python tries __str__ first. If it’s not defined, Python falls back to __repr__. If neither exists, you get the default <object at 0x...> representation.
Basic Example
Here’s a minimal but complete example:
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
def __str__(self):
return f"'{self.title}' - {self.pages} pages"
book = Book("The Pragmatic Programmer", 352)
print(book) # 'The Pragmatic Programmer' - 352 pages
print(str(book)) # 'The Pragmatic Programmer' - 352 pages
Notice: we return the string, not print it. The print() function calls __str__ internally.
__str__ vs __repr__
These two methods serve different purposes:
| Method | Audience | Purpose |
|---|---|---|
__str__ | End users | Human-readable, friendly |
__repr__ | Developers | Unambiguous, debug-friendly |
class Product:
def __init__(self, sku, name, price):
self.sku = sku
self.name = name
self.price = price
def __str__(self):
return f"{self.name} - ${self.price:.2f}"
def __repr__(self):
return f"Product(sku='{self.sku}', name='{self.name}', price={self.price})"
p = Product("SKU-123", "Wireless Mouse", 29.99)
print(str(p)) # Wireless Mouse - $29.99
print(repr(p)) # Product(sku='SKU-123', name='Wireless Mouse', price=29.99)
Use __str__ for what users see. Use __repr__ for what developers need to recreate the object.
Common Gotchas
Forgetting to return
def __str__(self):
print(self.name) # WRONG - this prints, doesn't return
# Result: TypeError: __str__ returned non-string (type NoneType)
Fix: Always return the string:
def __str__(self):
return self.name # Correct
Returning non-string types
def __str__(self):
return 42 # TypeError - must return str
def __str__(self):
return {"name": "Alice"} # TypeError - dict is not str
Fix: Convert to string:
def __str__(self):
return str(42) # Returns "42"
def __str__(self):
return str({"name": "Alice"}) # Returns "{'name': 'Alice'}"
Confusing with __repr__
Don’t define __repr__ and expect it to work as __str__. They have different audiences. If you only define __repr__, Python uses it as a fallback when __str__ is called—but the reverse isn’t true.
Practical Examples
Formatted output for data classes
class Transaction:
def __init__(self, id, amount, currency, date):
self.id = id
self.amount = amount
self.currency = currency
self.date = date
def __str__(self):
return f"Transaction #{self.id}: {self.amount} {self.currency} on {self.date}"
tx = Transaction("TXN-001", 150.00, "USD", "2024-01-15")
print(tx)
# Transaction #TXN-001: 150.0 USD on 2024-01-15
Status representation
class Server:
def __init__(self, name, status, uptime_hours):
self.name = name
self.status = status
self.uptime_hours = uptime_hours
def __str__(self):
emoji = "✅" if self.status == "healthy" else "❌"
return f"{emoji} {self.name}: {self.status} (uptime: {self.uptime_hours}h)"
s1 = Server("web-01", "healthy", 720)
s2 = Server("db-01", "down", 0)
print(s1) # ✅ web-01: healthy (uptime: 720h)
print(s2) # ❌ db-01: down (uptime: 0h)
Truncating long output
class LogEntry:
def __init__(self, message):
self.message = message
def __str__(self):
if len(self.message) > 50:
return self.message[:47] + "..."
return self.message
entry = LogEntry("This is a very long log message that exceeds the display width")
print(entry) # This is a very long log message that exceeds t...
Summary
__str__defines what users see when an object is printed or converted to string- It must return a string, not print it
- Called automatically by
print(),str(), and f-strings - Falls back to
__repr__if not defined - Keep it human-readable and friendly—leave the technical details to
__repr__
Define __str__ whenever you want clean, meaningful output for the end users of your code.