Overview
In Python, objects are rarely strings by default, yet APIs, logs, and user interfaces often need text representations. Converting an object to a string reliably requires choosing the right tool for the context: readable output, unambiguous debugging, structured interchange, or persistence. This guide explains the standard approaches—str(), repr(), formatted string literals, json serialization, and pickle—and when to use each. You will learn behavior for built‑ins and custom classes, encoding considerations, performance implications, and common pitfalls.
Key behaviors of str() and repr()
str() for end‑user output
The str(obj) function calls obj.__str__() when available and falls back to obj.__repr__(). The contract is to produce a readable, informal representation suitable for display. For example:
str(42)returns'42'.str('hello')returns'hello'.str([1, 2])returns'[1, 2]'.str(None)returns'None'.str(True)returns'True'.
Many built‑ins are already clear and safe; custom classes should implement __str__ for user friendly summaries.
repr() for unambiguous debugging
The repr(obj) function calls obj.__repr__(). The convention is that the result looks like a valid Python expression that could reconstruct the object, if feasible. Examples include:
repr(42)returns'42'.repr([1, 2])returns'[1, 2]'.repr('hello')wraps in quotes:''hello''.
If a class does not define __repr__, Python provides a default like MyClass object at 0x... . Use repr() in logs and debugging where precision matters.
| Function | Primary purpose | Output example (42) | Goal |
|---|---|---|---|
| str(obj) | Readable display | '42' | End‑user output |
| repr(obj) | Unambiguous debugging | '42' | Development and logging |
Formatted string literals and .format()
f‑strings (Python 3.6+)
F‑strings offer a concise, performant way to embed expressions as strings. The expression inside {...} uses __format__, and by default calls __str__. Examples:
value = 3.14159; f'{value}'produces'3.14159'.name = 'Alice'; f'Hello, {name}'produces'Hello, Alice'.f'{value:.2f}'formats to'3.14'.
Use explicit conversion inside the expression when needed: f'{obj!r}' calls repr(obj), while f'{obj!s}' calls str(obj).
.format() and legacy approaches
The '{}'.format(obj) method also calls str(obj) by default. For legacy code, '%s' % obj similarly converts via str. Explicit conversions remain possible with %r or {!r} for repr style output.
Custom classes and __str__ / __repr__
By default, instances of user defined classes show a memory address unless the methods are defined. Good practice is to implement both:
__repr__should be unambiguous and, if possible, look like a reconstructable expression.__str__can provide a concise, human friendly summary.
Example skeleton:
class Item:
def __init__(self, name, quantity):
self.name = name
self.quantity = quantity
def __repr__(self):
return f'Item(name={self.name!r}, quantity={self.quantity!r})'
def __str__(self):
return f'{self.name}: {self.quantity}'
With these methods, str(item) yields a clean label and repr(item) yields a detailed developer view.
Converting complex objects: JSON and serialization
json.dumps for serializable objects
The standard library’s json.dumps(obj) converts many built‑in types to a JSON string and calls default for unknown objects. It supports basic containers, numbers, strings, booleans, and None>. For custom objects, provide a default handler:
json.dumps(obj, default=lambda o: o.__dict__)serializes instance attributes when possible.- Dates and non‑serializable fields must be handled explicitly.
pickle for Python‑specific persistence
The pickle module serializes an object to bytes, supporting most Python types, including custom classes. Use it only in trusted environments:
pickle.dumps(obj)returns a bytes object.pickle.loads(data)reconstructs the object.
JSON is portable and safe; pickle is powerful and Python specific.
Best practices and common pitfalls
Safety and encoding
When producing text for network protocols or files, explicitly choose an encoding such as UTF‑8. For JSON, ensure non‑ASCII characters are handled via ensure_ascii=False or proper escaping. Never rely on implicit platform defaults.
Recursion and circular references
str(), repr(), and json.dumps can fail on self referential objects. Use reprlib to cap output size or implement custom serialization with cycle detection for complex graphs.
Performance notes
str()is typically fast and suitable for UI and logging.repr()may be costlier for deeply nested structures.- JSON serialization involves overhead but is acceptable for interchange and moderate‑size payloads.
Quick reference table
| Technique | Use case | Handles custom class out of box? | Output example (Item('apples', 3)) |
|---|---|---|---|
| str(obj) | Human readable output | Only if __str__ defined | 'apples: 3' |
| repr(obj) | Debugging | Only if __repr__ defined | 'Item(name='apples', quantity=3)' |
| f'{obj}' | Embedding in text | Only if __str__ defined | 'apples: 3' |
| f'{obj!r}' | Embedding repr safely | Only if __repr__ defined | 'Item(name='apples', quantity=3)' |
| json.dumps(obj) | Interchange / config files | Only for JSON‑compatible subset or with default handler | '{\"name\": \"apples\", \"quantity\": 3}' |
| pickle.dumps(obj) | Python‑specific persistence | Yes, for most objects | b'\x80\x04\x95…' (binary) |
When to use each method
- For display to users:
str(obj)or anf'{obj}'. - For logs and debugging:
repr(obj)orf'{obj!r}'. - For configuration or data interchange:
json.dumps, ensuring the object is JSON serializable. - For preserving object state inside Python:
pickle.dumps.
Conclusion
Converting an object to a string in Python is straightforward once you align the method with the purpose: str() and f‑strings for readable output, repr() for unambiguous debugging, json.dumps for portable interchange, and pickle for Python‑specific persistence. Implement __str__ and __repr__ on your own classes to make conversion predictable. With these tools, you can handle display, logging, serialization, and interoperability needs safely and efficiently.
Related topics
- String formatting guide
- Python serialization strategies
- Custom class representation best practices