ScanSkill

repr

This repr() function returns a string containing a printable representation of an object.

Syntax

repr(*object*)

Here,

  • object: Required. A valid python object.

Note: For many types, repr() function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets.

Examples

>>> repr(1)
'1'
>>> repr([1, 2])
'[1, 2]'
>>> repr({'a': 1, 'b': 2})
"{'a': 1, 'b': 2}"
>>> repr('hello')
"'hello'"
>>> repr("hello")
"'hello'"
>>> repr("""hello""")
"'hello'"
>>> repr('hello')
"'hello'"
>>> eval(repr('hello'))
'hello'

Here, repr(’hello’) returned “’hello’”, inside double quotes while passing repr() to *eval()* returned just ‘hello’.

  • Custom objects
>>> class class1:
...     pass
...
>>> repr(class1())
'<__main__.class1 object at 0x7efe541b9120>'
  • Custom objects with __repr__() (override/implement)
>>> class class2:
...     def __repr__(self):
...         return 'class2 output'
...
>>> repr(class2())
'class2 output'