Python repr() Function
Python repr() Function returns a printable representation of an object in Python.
Python repr() Function Syntax:
Syntax: repr(object)
- object: The object whose printable representation is to be returned.
Return: str, printable representation of the object.
Python repr() Function Example
Python3
print ( repr ([ 'a' , 'b' , 'c' ])) |
Output:
['a', 'b', 'c']
Example 1: Passing string object to repr() method
Python3
strObj = 'geeksforgeeks' print ( repr (strObj)) |
Output:
'geeksforgeeks'
Example 2: Passing set object to repr() method
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}
Example 3: Defining __repr__() method in class
Inside a class, we can define __repr__() method to override repr() function call behavior on the object of the class.
Python3
class Person: def __init__( self , name): self .name = name def __repr__( self ): return f 'Person("{self.name}")' p = Person( "Kiran" ) # returns a string which can be used to recontruct Person object print ( repr (p)) |
Output:
Person("Kiran")
Please Login to comment...