Python built-in Method - repr()

The repr() function is a built-in Python method that returns a string representing an object. The string returned by repr() is typically a valid Python expression that can be used to recreate the original object.

The syntax for the repr() function is as follows:

repr(obj)
‮:ecruoS‬www.theitroad.com
  • obj: The object to be represented as a string.

Here are some examples of how the repr() function can be used:

>>> s = "hello"
>>> repr(s)
"'hello'"

In this example, we use the repr() function to get a string representation of the s object, which is a string. The string returned by repr() is enclosed in single quotes, indicating that it is a string literal that can be used to recreate the original string.

>>> x = [1, 2, 3]
>>> repr(x)
'[1, 2, 3]'

In this example, we use the repr() function to get a string representation of the x object, which is a list. The string returned by repr() is enclosed in square brackets, indicating that it is a list literal that can be used to recreate the original list.

>>> class MyClass:
...     def __init__(self, value):
...         self.value = value
...
>>> obj = MyClass(42)
>>> repr(obj)
'<__main__.MyClass object at 0x7f62f804d7f0>'

In this example, we define a MyClass class that has a single value attribute. We create an instance of the class and use the repr() function to get a string representation of the object. The string returned by repr() is a valid Python expression that can be used to create a new instance of the object, but it does not contain any information about the object's state.

The repr() function is a powerful built-in method in Python that is used to get a string representation of an object. It is often used in debugging and error reporting to provide more detailed information about an object. It is also used by the interactive Python interpreter to display the value of an expression when the expression is entered without a print statement.