VOOZH about

URL: https://www.geeksforgeeks.org/python/python-repr-function/

⇱ Python repr() Function - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python repr() Function

Last Updated : 23 Jul, 2025

The repr() function in Python is used to return a string representation of an object that can be used to recreate the object when passed to eval(). It is mainly used for debugging and logging because it provides an unambiguous representation of an object.

To understand more clearly, think of repr() as a blueprint for an object, while str() is a user-friendly description of it. Let's take an example:


Output
Hello
World
'Hello\nWorld'

Explanation:

  • str(text) prints the actual output, where \n creates a newline.
  • repr(text) gives the precise representation with escape characters so that the output can be recreated in code.

This shows that repr() is meant for debugging and object recreation, while str() is for user-friendly display.

Syntax

repr(object)

Parameters:

  • object- object whose printable representation is to be returned.

Return Type: repr() function returns a string (str) representation of the given object (<class 'str'>).

Examples of repr() method

1. Using repr() on Different Data-Types

Using repr() function on any data-type converts it to a string object.


Output
42 <class 'str'>
'Hello, Geeks!' <class 'str'>
[1, 2, 3] <class 'str'>
{1, 2, 3} <class 'str'>

Explanation:repr(object) function returns a string representation of all the data-types, preserving their structure, and type(repr(l)) confirms that the output is of type str.

2. Using repr() with Custom Classes

__repr__ method in custom classes defines how an object is represented as a string. It helps in debugging by showing useful details about the object. Here's an example:


Output
Person('Geek', 9)

Explanation:

  • __repr__ method is overridden to return a detailed string representation of the Person object.
  • repr(g) prints "Person('Geek', 9)", making the data of the object clear.

3. Recreating Object Using eval()

In the previous example, we can recreate the Person object from the converted str object by repr() funtion using eval() function, here's how:


Output
Person('Alice', 25)
Person('Alice', 25)
Person('Alice', 25)
Alice 25

Explanation:

  • eval(repr(p)) evaluates this string as code, effectively creating a new Person object.
  • The new object p_new is now an independent instance but has the same values as p.
  • This demonstrates the true purpose of repr()-providing a string representation that allows object recreation which is not possible with str() method.

To know the difference between str and repr Click here.

Comment
Article Tags: