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 Machine Learning - Sebastian Raschka
Python Program to Remove Punctuations From a String
Python Modules
Python Namespace and Scope
Python set()
Python Input, Output and Import
Python String capitalize()
Python zip()
Deep Learning in Python - LazyProgrammer
Python Exception Handling Using try, except and finally statement
Python Set difference_update()
Python Program to Check if a Number is Odd or Even
Python Program to Check Armstrong Number
Python Program Read a File Line by Line Into a List
Python String rstrip()
Python Dictionary popitem()
Python Program to Check Whether a String is Palindrome or Not
Python Set symmetric_difference()
Python String index()
Python enumerate()
Python List index()
Python ord()
Python String casefold()
Python Set issuperset()
Python String rpartition()
Python Program to Calculate the Area of a Triangle
Python Program to Iterate Over Dictionaries Using for Loop
Python Program to Find ASCII Value of Character
Python Decorators
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python divmod()
Python Program to Access Index of a List Using for Loop