In Python, the str() and repr() functions are used to obtain string representations of objects. While they may seem similar at first glance, there are some differences in how they behave. Both of the functions can be helpful in debugging or printing useful information about the object.
Python str()
In the given example, we are using the str() function on a string and floating values in Python.
Python3
s = 'Hello, Geeks.'
print ( str (s))
print ( str ( 2.0 / 11.0 ))
|
Output:
Hello, Geeks.
0.181818181818
Python repr()
In the given example, we are using the repr() function on a string and floating values in Python.
Python3
s = 'Hello, Geeks.'
print ( repr (s))
print ( repr ( 2.0 / 11.0 ))
|
Output:
'Hello, Geeks.'
0.18181818181818182
str() vs repr() in Python Examples
From the above output, we can see if we print a string using the repr() function then it prints with a pair of quotes and if we calculate a value we get a more precise value than the str() function.
Python __str__() and __repr__() with a Built-In Class
In this example, we are creating a DateTime object of the current time and we are printing it into two different formats.
str() displays today’s date in a way that the user can understand the date and time. repr() prints an “official” representation of a date-time object (means using the “official” string representation we can reconstruct the object).
Python3
import datetime
today = datetime.datetime.now()
print ( str (today))
print ( repr (today))
|
Output :
2016-02-22 19:32:04.078030
datetime.datetime(2016, 2, 22, 19, 32, 4, 78030)
How to make them work for our own defined classes?
A user-defined class should also have a __repr__() if we need detailed information for debugging. And if we think it would be useful to have a string version for users, we create a __str__() function. In this example, We have created a class Complex which has two instance variables real and imag. We are creating custom __repr__() and __str__() methods in the class.
Python3
class Complex :
def __init__( self , real, imag):
self .real = real
self .imag = imag
def __repr__( self ):
return 'Rational(%s, %s)' % ( self .real, self .imag)
def __str__( self ):
return '%s + i%s' % ( self .real, self .imag)
t = Complex ( 10 , 20 )
print ( str (t))
print ( repr (t))
|
Output :
10 + i20
Rational(10, 20)
Difference between Python str() and Python repr()
Points
|
str()
|
repr()
|
Return Value
|
Returns a human-readable string representation of the object
|
Returns an unambiguous string representation of the object
|
Usage
|
Used for creating user-friendly output and for displaying the object as a string
|
Used for debugging and development purposes to get the complete information of an object
|
Examples
|
str(123) returns ‘123’
|
repr(123) returns ‘123’
|
|
str(‘hello’) returns ‘hello’
|
repr(‘hello’) returns “‘hello'”
|
|
str([1, 2, 3]) returns ‘[1, 2, 3]’
|
repr([1, 2, 3]) returns ‘[1, 2, 3]’
|
|
str({‘name’: ‘John’, ‘age’: 30}) returns “{‘name’: ‘John’, ‘age’: 30}”
|
repr({‘name’: ‘John’, ‘age’: 30}) returns “{‘name’: ‘John’, ‘age’: 30}”
|
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!