The repr() function in Python is a built-in function that returns a string representing a printable version of an object. The repr() function returns a string that, if evaluated, would produce an object with the same value as the original object. The repr() function is intended to be used for debugging and development purposes.
Syntax
repr(object)
Parameters
- object : The object for which a string representation is returned.
Return Value
The repr() function returns a string representing a printable version of an object.
Examples
Example 1: repr() with Integer
# repr() with integer number = 10 print(repr(number))
Output
10
In this example, the repr() function is used to return a string representation of the integer “number”. The string representation of the integer is then printed to the console.
Example 2: repr() with String
# repr() with string word = "Hello" print(repr(word))
Output
'Hello'
In this example, the repr() function is used to return a string representation of the string “word”. The string representation of the string is then printed to the console.
Example 3: repr() with List
# repr() with list numbers = [1, 2, 3, 4, 5] print(repr(numbers))
Output
[1, 2, 3, 4, 5]
In this example, the repr() function is used to return a string representation of the list “numbers”. The string representation of the list is then printed to the console.
Use Cases
The repr() function can be used for debugging purposes, such as printing the representation of an object to the console for inspection. It can also be used to convert an object to a string representation that can be stored in a file or database. For example, in a web application, the repr() function can be used to store a string representation of an object in a database for later retrieval and use.
Additionally, the repr() function can be used to customize the string representation of an object for display purposes. By defining a custom __repr__() method for a class, you can control the string representation of objects of that class, which can be useful for debugging or for displaying information to the user in a specific format.
Another use case of the repr() function is in testing and assertion. The repr() function can be used to compare the string representation of two objects, and to check if they are equal. This can be useful in writing tests for your code, to make sure that objects are being constructed and used correctly.
In summary, the repr() function is a powerful tool in Python, providing a way to get a string representation of an object that is both human-readable and machine-readable. Whether for debugging, testing, or displaying information to the user, the repr() function is an important tool to have in your Python toolkit.