Table of Contents
In this tutorial, we will learn about the Python repr() function with the help of examples.
The repr()
function returns a printable representation of the given object.
Example
numbers = [1, 2, 3, 4, 5] # create a printable representation of the list printable_numbers = repr(numbers) print(printable_numbers) # Output: [1, 2, 3, 4, 5]
1. repr() Syntax
The syntax of repr()
is:
repr(obj)
2. repr() Parameters
The repr()
function takes a single parameter:
- obj – the object whose printable representation has to be returned
3. repr() Return Value
The repr()
function returns a printable representational string of the given object.
4. Example 1: How repr() works in Python?
var = 'foo' print(repr(var))
Output
'foo'
Here, we assign a value 'foo'
to var. Then, the repr()
function returns "'foo'"
, 'foo'
inside double-quotes.
When the result from repr()
is passed to eval()
, we will get the original object (for many types).
>>> eval(repr(var)) 'foo'
5. Example 2: Implement __repr__() for custom objects
Internally, repr()
function calls __repr__()
of the given object.
You can easily implement/override __repr__()
so that repr()
works differently.
class Person: name = 'Adam' def __repr__(self): return repr('Hello ' + self.name ) print(repr(Person()))
Output
'Hello Adam'
Related posts:
Python String partition()
Python Program to Capitalize the First Character of a String
Python Program to Shuffle Deck of Cards
Python strptime()
Python Set isdisjoint()
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python Decorators
Python Set update()
Python reversed()
Python String expandtabs()
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python String istitle()
Python RegEx
Python Machine Learning Eqution Reference - Sebastian Raschka
Python Program to Get the Last Element of the List
Python Program to Access Index of a List Using for Loop
Python Tuple count()
Python while Loop
Python hasattr()
Python Custom Exceptions
Python Program to Compute the Power of a Number
Python Program to Get File Creation and Modification Date
Python type()
Python Program to Find the Largest Among Three Numbers
Python Program to Sort a Dictionary by Value
Python setattr()
Python bin()
Python Program to Randomly Select an Element From the List
Python Program to Get the Class Name of an Instance
Python String index()
Python Set issubset()
Python sorted()