Open In App

Python repr() Function

Improve
Improve
Like Article
Like
Save
Share
Report

Python repr() Function returns a printable representation of an object in Python. In other words, we can say that the Python repr() function returns a printable representation of the object by converting that object to a string.

Example

In the code, repr(s) returns the string ‘Hello, Geeks.’ enclosed in single quotes. repr(2.0/11.0) calculates the division of 2.0 by 11.0 and returns the result as a string without any formatting or rounding.

Python3




s = 'Hello, Geeks.'
print (repr(s))
print (repr(2.0/11.0))


Output :

'Hello, Geeks.'
0.18181818181818182

Python repr() Function Syntax

Syntax: repr(object)

  • object: The object whose printable representation is to be returned.

Return: str, printable representation of the object.

How repr() works in Python?

Here we assign an integer value of 10 to a variable x and the repr() of x is returning the value 10 as a string class.

Python3




x = 10
print(type(repr(x)))


Output :

<class 'str'>

repr() in Python Examples

Passing List to repr() in Python

In this example, we are using repr() on the list.

Python3




print(repr(['a', 'b', 'c']))


Output :

['a', 'b', 'c']

Passing string object to repr() method

In this example, we are calling the repr() on the string object in Python.

Python3




strObj = 'geeksforgeeks'
 
print(repr(strObj))


Output :

'geeksforgeeks'

Passing a set object to the repr() method

In this example, we have created a set. The set includes numbers from 1 to 5 and we are calling the repr() on the set.

Python3




num = {1, 2, 3, 4, 5}
 
# printable representation of the set
printable_num = repr(num)
print(printable_num)


Output :

{1, 2, 3, 4, 5}

Implement __repr__() for custom objects

In this example, the Person class has a __repr__() method that returns a string representation of the Person object. The repr(person) call returns the string representation defined by the __repr__() method, which is then printed to the console.

Python3




class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    def __repr__(self):
        return f"Person(name='{self.name}', age={self.age})"
 
person = Person("John", 25)
print(repr(person))


Output :

Person(name='John', age=25)

To know the difference between str and repr Click here.



Last Updated : 27 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads