In Python, the repr() function is a built-in function that returns a string representation of an object. The repr() function is short for "representation" and is used to generate a printable representation of an object that can be used to recreate the object. The repr() function can be called on any object in Python, and the output of the function is a string that can be printed to the console or used in other parts of a program.
The basic syntax for the repr() function is as follows:
|
repr(object)
|
where object is the object for which you want to generate a string representation.
Here are some examples of using the repr() function:
Example 1: Generating a string representation of an integer
|
x = 42
print(repr(x))
|
Output:
42
In this example, the repr() function is called on the integer 42, which generates a string representation of the integer. Since the input is already an integer, the output of the repr() function is the same as the input.
Example 2: Generating a string representation of a string
|
x = "Hello, world!"
print(repr(x))
|
Output:
'Hello, world!'
In this example, the repr() function is called on the string "Hello, world!", which generates a string representation of the string. The output of the repr() function is a string with quotes around it to indicate that it is a string.
Example 3: Generating a string representation of a list
|
x = [1, 2, 3, 4, 5] print(repr(x))
|
Output:
[1, 2, 3, 4, 5]
In this example, the repr() function is called on a list of integers [1, 2, 3, 4, 5]. The output of the repr() function is a string representation of the list, which can be used to recreate the list.
Example 4: Generating a string representation of a custom object
|
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person(name={self.name}, age={self.age})"
p = Person("John", 42)
print(repr(p))
|
Output:
Person(name=John, age=42)
In this example, the repr() function is called on a custom Person object. The __repr__() method is defined in the Person class to generate a string representation of the object. The output of the repr() function is a string that can be used to recreate the Person object.
In conclusion, the repr() function is a useful tool in Python for generating a string representation of an object that can be used in various parts of a program. The repr() function can be called on any object in Python, and the output of the function is a string that can be printed to the console or used in other parts of the code. By mastering the repr() function, you can write more efficient and concise Python code.