The repr()
function returns a string that represents an object exactly as it is. It’s useful for debugging, logging, and generating code-friendly representations of objects.
Example
text = "Hello, World!"
print(repr(text))
Output:
'Hello, World!'
The quotes are included to show it’s a string.
Syntax
repr(object)
- object → The object to represent as a string.
- Returns → A string containing the official representation of the object.
1. Using repr()
on Different Data Types
print(repr(100)) # Output: '100'
print(repr(3.14)) # Output: '3.14'
print(repr("Python")) # Output: "'Python'"
print(repr([1, 2, 3])) # Output: '[1, 2, 3]'
print(repr({"key": "value"})) # Output: "{'key': 'value'}"
It preserves data structures.
2. Difference Between repr()
and str()
text = "Hello\nWorld"
print(str(text)) # Output: Hello
# World
print(repr(text)) # Output: 'Hello\nWorld'
str()
→ Prints in a human-friendly format.repr()
→ Preserves escapes (\n
) and quotes.
3. Using repr()
for Debugging
user_input = " 123 "
print(f"User input: {repr(user_input)}")
# Output: "User input: ' 123 '"
Makes invisible characters like spaces clear.
4. Defining repr()
in a Custom Class
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("Alice", 30)
print(repr(p))
# Output: Person(name='Alice', age=30)
Defines an exact string representation of the object.
5. Evaluating repr()
Output with eval()
x = [1, 2, 3]
repr_x = repr(x)
print(eval(repr_x)) # Output: [1, 2, 3]
eval(repr(obj))
reconstructs the original object.
Key Notes
- ✔ Returns an exact representation of an object.
- ✔ Preserves quotes, escapes, and data structures.
- ✔ Useful for debugging and logging.
- ✔ Works with
eval()
to recreate objects.
By using repr()
, you can debug more effectively, log precise values, and generate accurate object representations. 🚀