Python repr() Function



The Python repr() function is used to obtain a string representation of an object.

This function is useful for debugging and logging purposes as it provides a detailed and clear representation of an object compared to the str() function. While str() is mainly used to create human-readable strings, repr() provides a string that, when passed to the eval() function, can recreate the original object.

Syntax

Following is the syntax of Python repr() function −

repr(x)

Parameters

This function takes an object 'x' as a parameter for which you want to obtain the string representation.

Return Value

This function returns a string that, when executed as Python code, would recreate the original object.

Example

In the following example, we are using the repr() function to obtain the string representation of the string object "Hello, World!" −

text = "Hello, World!"
representation = repr(text)
print('The string representation obtained is:',representation)

Output

Following is the output of the above code −

The string representation obtained is: 'Hello, World!'

Example

Here, we are using the repr() function to obtain the string representation of an integer object "42" −

number = 42
representation = repr(number)
print('The string representation obtained is:',representation)

Output

Output of the above code is as follows −

The string representation obtained is: 42

Example

In here, we are obtaining the string representation of the list "[1, 2, 3]". The output is a string that, when used in Python code, would recreate the original list −

my_list = [1, 2, 3]
representation = repr(my_list)
print('The string representation obtained is:',representation)

Output

The result obtained is as shown below −

The string representation obtained is: [1, 2, 3]

Example

In this case, the repr() function is used with a complex number "(2+3j)" −

complex_num = complex(2, 3)
representation = repr(complex_num)
print('The string representation obtained is:',representation)

Output

Following is the output of the above code −

The string representation obtained is: (2+3j)

Example

In this example, we define a custom class called "Point" with "x" and "y" attributes to represent coordinates. Additionally, we implement a "repr" method within the class to customize the string representation. Afterward, we create an instance of the class named "point_instance" with coordinates "(1, 2)". By using the repr() function, we obtain the formatted string "Point(1, 2)" representing the coordinates of the point −

class Point:
   def __init__(self, x, y):
      self.x = x
      self.y = y
   def __repr__(self):
      return f'Point({self.x}, {self.y})'
point_instance = Point(1, 2)
representation = repr(point_instance)
print('The string representation obtained is:',representation)

Output

The result produced is as follows −

The string representation obtained is: Point(1, 2)
python-repr-function.htm
Advertisements