Python 3 reference · Built-in Functions
Python repr() Function
Return the developer-friendly string representation of an object, often valid Python code that recreates the value.
Python 3 Since 3.0
Syntax
repr(object)
Parameters
| Parameter | Description |
|---|---|
object |
Any object. |
Return value
A str.
Examples
text = "hi\nthere"
print(str(text))
print(repr(text))
print(repr(3.0), repr([1, "a"]))
Output
hi there 'hi\nthere' 3.0 [1, 'a']
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return f"Point(x={self.x}, y={self.y})"
print(repr(Point(1, 2)))
print([Point(0, 0)]) # containers use repr() for their items
Output
Point(x=1, y=2) [Point(x=0, y=0)]
name = "Ada"
print(f"{name!r}") # !r uses repr() inside f-strings
Output
'Ada'
Good to know
str() is for end users; repr() is for developers (logs, debugging, the REPL). Give every class a
__repr__(); lists and dicts show their items with it.
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
str()· Convert a value to its readable text form, or decode bytes into a string. Strings are immutable sequences of characters.ascii()· Return a printable representation of an object, like repr(), but with every non-ASCII character escaped.format()· Format a single value with a format spec, such as format(3.14159, '.2f') giving '3.14'. The same mini-language as f-strings.print()· Write values to standard output (or a file), separated by spaces and followed by a newline. Both are configurable.- Python Strings · tutorial
- Python Classes and Objects · tutorial