Python @ DjangoSpin

Python: When to use repr() & str() functions

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

repr() & str() in Python

repr() & str() in Python

The builtin repr() function returns a string containing the printable representation of an object. Each Python object, be it lists, sets, tuples etc. has a magic method __repr__ (Learn more about magic methods here) which is called implicitly when repr() is called on them. Let's look at a few examples.

>>> repr('string')
"'string'"
>>> repr(4)
'4'
>>> repr( set( [1, 2, 'three', 'four'] ) )
"{1, 2, 'four', 'three'}"
>>> repr( [1, 2, 'three', 'four'] )
"[1, 2, 'three', 'four']"
>>> repr( (1, 2, 'three', 'four') )
"(1, 2, 'three', 'four')"
>>> 
>>> 
>>> 
>>> str('string')
'string'
>>> str(4)
'4'
>>> str( set( [1, 2, 'three', 'four'] ) )
"{1, 2, 'four', 'three'}"
>>> str( [1, 2, 'three', 'four'] )
"[1, 2, 'three', 'four']"
>>> str( (1, 2, 'three', 'four') )
"(1, 2, 'three', 'four')"

There is a little difference between the outputs of the repr() and str() with same inputs, as seen in examples above. The str(object) calls the __str__ magic method of the object, if defined. The str(object) returns the "informal" or nicely printable string representation of the object. If the object does not have a __str__ method, then str(object) returns the string returned by repr(object) .

One important thing to note about the repr() function is that it keeps the escape sequences intact, and does not interpret them, like we saw in the BufferedReader code. This behavior is in contrast to the str() function.

In a nutshell, the __repr__() method of an object is defined to make it unambiguous, whereas the __str__() method is defined to make the object readable.


See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply