The repr() function in Python is used to return a string representation of an object that can be used to recreate the object when passed to eval(). It is mainly used for debugging and logging because it provides an unambiguous representation of an object.
To understand more clearly, think of repr() as a blueprint for an object, while str() is a user-friendly description of it. Let's take an example:
Python
text = "Hello\nWorld"
print(str(text))
print(repr(text))
OutputHello
World
'Hello\nWorld'
Explanation:
- str(text) prints the actual output, where \n creates a newline.
- repr(text) gives the precise representation with escape characters so that the output can be recreated in code.
This shows that repr() is meant for debugging and object recreation, while str() is for user-friendly display.
Syntax
repr(object)
Parameters:
- object- object whose printable representation is to be returned.
Return Type: repr() function returns a string (str) representation of the given object (<class 'str'>).
Examples of repr() method
1. Using repr() on Different Data-Types
Using repr() function on any data-type converts it to a string object.
Python
a = 42 # passing int
print(repr(a), type(repr(a)))
s = "Hello, Geeks!" # passing string
print(repr(s), type(repr(s)))
l = [1, 2, 3] # passing list
print(repr(l), type(repr(l)))
st = {1, 2, 3} # passing set
print(repr(st), type(repr(st)))
Output42 <class 'str'>
'Hello, Geeks!' <class 'str'>
[1, 2, 3] <class 'str'>
{1, 2, 3} <class 'str'>
Explanation: repr(object) function returns a string representation of all the data-types, preserving their structure, and type(repr(l)) confirms that the output is of type str.
2. Using repr() with Custom Classes
__repr__ method in custom classes defines how an object is represented as a string. It helps in debugging by showing useful details about the object. Here's an example:
Python
class Person:
def __init__(self, n, a):
self.name = n
self.age = a
def __repr__(self):
return f"Person('{self.name}', {self.age})"
g = Person("Geek", 9)
print(repr(g))
Explanation:
- __repr__ method is overridden to return a detailed string representation of the Person object.
- repr(g) prints "Person('Geek', 9)", making the data of the object clear.
3. Recreating Object Using eval()
In the previous example, we can recreate the Person object from the converted str object by repr() funtion using eval() function, here's how:
Python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person('{self.name}', {self.age})"
# Creating an object
p = Person("Alice", 25)
# Printing str and repr
print(str(p))
print(repr(p))
# Recreating the object using eval()
p_new = eval(repr(p))
print(p_new)
print(p_new.name, p_new.age)
OutputPerson('Alice', 25)
Person('Alice', 25)
Person('Alice', 25)
Alice 25
Explanation:
- eval(repr(p)) evaluates this string as code, effectively creating a new Person object.
- The new object p_new is now an independent instance but has the same values as p.
- This demonstrates the true purpose of repr()-providing a string representation that allows object recreation which is not possible with str() method.
To know the difference between str and repr Click here.
Similar Reads
Python str() function The str() function in Python is an in-built function that takes an object as input and returns its string representation. It can be used to convert various data types into strings, which can then be used for printing, concatenation, and formatting. Letâs take a simple example to converting an Intege
3 min read
Python Functions Python Functions is a block of statements that return the specific task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it ov
11 min read
type() function in Python The type() function is mostly used for debugging purposes. Two different types of arguments can be passed to type() function, single and three arguments. If a single argument type(obj) is passed, it returns the type of the given object. If three argument types (object, bases, dict) are passed, it re
5 min read
Python int() Function The Python int() function converts a given object to an integer or converts a decimal (floating-point) number to its integer part by truncating the fractional part.Example:In this example, we passed a string as an argument to the int() function and printed it.Pythonage = "21" print("age =", int(age)
3 min read
round() function in Python Python round() function is a built-in function available with Python. It will return you a float number that will be rounded to the decimal places which are given as input. If the decimal places to be rounded are not specified, it is considered as 0, and it will round to the nearest integer. In this
6 min read
Python len() Function The len() function in Python is used to get the number of items in an object. It is most commonly used with strings, lists, tuples, dictionaries and other iterable or container types. It returns an integer value representing the length or the number of elements. Example:Pythons = "GeeksforGeeks" # G
2 min read
sum() function in Python The sum of numbers in the list is required everywhere. Python provides an inbuilt function sum() which sums up the numbers in the list. Pythonarr = [1, 5, 2] print(sum(arr))Output8 Sum() Function in Python Syntax Syntax : sum(iterable, start) iterable : iterable can be anything list , tuples or dict
3 min read
Python print() function The python print() function as the name suggests is used to print a python object(s) in Python as standard output. Syntax: print(object(s), sep, end, file, flush) Parameters: Object(s): It can be any python object(s) like string, list, tuple, etc. But before printing all objects get converted into s
2 min read
Python User Defined Functions A User-Defined Function (UDF) is a function created by the user to perform specific tasks in a program. Unlike built-in functions provided by a programming language, UDFs allow for customization and code reusability, improving program structure and efficiency.Example:Python# function defination def
6 min read
chr() Function in Python chr() function returns a string representing a character whose Unicode code point is the integer specified. chr() Example: Python3 num = 97 print("ASCII Value of 97 is: ", chr(num)) OutputASCII Value of 97 is: a Python chr() Function Syntaxchr(num) Parametersnum: an Unicode code integerRet
3 min read