str() vs repr() in Python

str() and repr() both are used to get a string representation of object.

Example of str():

filter_none

editclose

play_arrow

linkbrightness_4code

s ='Hello, Geeks.'

printstr(s)

printstr(2.0/11.0)

chevron_right

filter_none

Output:

Hello, Geeks.
0.181818181818

.

Example of repr():

filter_none

editclose

play_arrow

linkbrightness_4code

s ='Hello, Geeks.'

printrepr(s)

printrepr(2.0/11.0)

chevron_right

filter_none

Output:

'Hello, Geeks.'
0.18181818181818182

From above output, we can see if we print string using repr() function then it prints with a pair of quotes and if we calculate a value we get more precise value than str() function.

Following are differences:

str() is used for creating output for end user while repr() is mainly used for debugging and development. repr’s goal is to be unambiguous and str’s is to be readable. For example, if we suspect a float has a small rounding error, repr will show us while str may not.

str() displays today’s date in a way that the user can understand the date and time.

repr() prints “official” representation of a date-time object (means using the “official” string representation we can reconstruct the object).

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.

filter_none

editclose

play_arrow

linkbrightness_4code

# Python program to demonstrate writing of __repr__ and

# __str__ for user defined classes

# A user defined class to represent Complex numbers

classComplex:

# Constructor

def__init__(self, real, imag):

self.real =real

self.imag =imag

# For call to repr(). Prints object's information

def__repr__(self):

return'Rational(%s, %s)'%(self.real, self.imag)

# For call to str(). Prints readable form

def__str__(self):

return'%s + i%s'%(self.real, self.imag)

# Driver program to test above

t =Complex(10, 20)

printstr(t) # Same as "print t"

printrepr(t)

chevron_right

filter_none

Output:

10 + i20
Rational(10, 20)

This article is contributed by Arpit Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above