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 max()
Python abs()
Python Numbers, Type Conversion and Mathematics
Python Global, Local and Nonlocal variables
Python Program to Find the Factorial of a Number
Python String expandtabs()
Python Anonymous / Lambda Function
Python issubclass()
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python Program to Find Armstrong Number in an Interval
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python List insert()
Python Program to Count the Number of Each Vowel
Python Program to Multiply Two Matrices
Python reversed()
Python del Statement
Python Program to Print all Prime Numbers in an Interval
Python Type Conversion and Type Casting
Python Program to Compute all the Permutation of the String
Python break and continue
Python while Loop
Python String index()
Python Dictionary update()
Python tuple()
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python List
Python Program to Check if a Number is Odd or Even
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python Program to Add Two Matrices
Python Program to Solve Quadratic Equation
Python String zfill()
Python sorted()