Python repr() Function
Returns a printable representation of the given object.
Syntax
Python
Copy Code
repr(object)
Parameters
Parameter | Description |
---|---|
object |
Required. The object to be represented as a string |
Example
Python
Copy Code
numbers = [1, 2, 3, 4, 5] printable = repr(numbers) print(printable)
Output
[1, 2, 3, 4, 5]
Notes
Many built in types already implement the _repr__()
function so the output is
the same wether one uses, in the example above, print(numbers)
or
print(repr(numbers))
. Classes will print a representation of
the class:
Example
Python
Copy Code
class MyClass(): pass print(repr(MyClass()))Output:
<__main__.MyClass object at 0x000001C42C271A08>
You can implement your own __repr__()
function to change the representation that is printed:
Example
Python
Copy Code
class MyClass(): def __repr__(self): return 'This is MyClass' print(repr(MyClass()))Output:
This is MyClass