The built-in function repr() in Python

The repr() built-in function in Python returns the string representation of an object. The Python code example given here returns the string representation for few basic types and for an user defined type.

Built-in Functions Updated 21 Jan 2023 1 min read

Overview

  • The Python built-in function repr() returns the string representation of an object.

Example

The Python code example below prints the string representation for an integer, a floating point number and an object of user defined class Banner. For the Banner object, the representation comes from the __repr__() method implemented in the Banner class.

python
# Example Python program that prints

            # the string reprsentation of objects

            # belonging to various types

            class Banner:

                def __init__(self, msg):

                    self.msg = msg

    def display(self):

                    print(contents)

    def __repr__(self):

                    return "<type:%s,id:%d,msg:%s>"%(__class__.__name__,id(self),self.msg)

# Get info about an int object

            val = 10

            print(repr(val))

            print(repr(type(val)))

# Get info about a floating point object

            val = 10.1

            print(repr(val))

            print(repr(type(val)))

# Get info about an instance of an user defined class

            simpleBanner = Banner("Hello World")

            print(repr(simpleBanner))

Output

Output
10

            <class 'int'>

            10.1

            <class 'float'>

            <type:Banner,id:4401581648,msg:Hello World>