str() vs repr() vs print() in Python
Source: Dev.to
Overview
When learning Python you encounter three built‑in utilities that often look similar:
str()repr()print()
At first they may seem to do the same thing—display output—but each has a distinct purpose.
str()
- Returns a user‑friendly (readable) representation of an object.
- Intended for display to end users.
- Example:
str("Hello\nWorld")yieldsHello\nWorld(the newline is interpreted).
repr()
- Returns a developer‑oriented (debugging) representation of an object.
- Shows the exact internal form that Python uses, including quotes and escape characters.
- Example:
repr("Hello\nWorld")yields'Hello\\nWorld', making the\nvisible.
print()
- Writes the string representation of an object to the console.
- Internally it calls
str()on the object before outputting it.
Comparison
| Function | Purpose |
|---|---|
str() | Human‑readable representation |
repr() | Precise, unambiguous representation for debugging |
print() | Display output (uses str() internally) |
Understanding the difference between readable output (str()) and the raw internal representation (repr()) clarifies Python’s behavior, especially when debugging or inspecting objects. This small concept is powerful for writing clear and maintainable code.