With the expression 'abc%rdef' % obj
, the part '%r'
is replaced with repr(obj)
With the expression 'ABC%sDEF' % obj
, the part '%s'
is replaced with str(obj)
.
repr() is a function that , for common objects, returns a string that is the same as the one you would write in a script to define the object passed as argument to the repr() function:
For many types, this function makes an attempt to return a string that
would yield an object with the same value when passed to eval()
http://docs.python.org/library/functions.html#repr
.
Example 1
if you consider the list defined by li = [12,45,'haze']
print li
will print [12,45,'haze']
print repr(li)
will also print [12,45,'haze'] , because [12,45,'haze']
is the sequence of characters that are written in a script to define the list li with this value
Example 2
if you consider the string defined by ss = 'oregon'
:
print ss
will print oregon , without any quote around
print repr(ss)
will print 'oregon' , since 'oregon'
is the sequence of characters that you must write in a script if you want to define the string ss with the value oregon in a program
.
So, this means that , in fact, for common objects, repr() and str() return strings that are in general equal, except for a string object. That makes repr() particularly interesting for string objects. It is very useful to analyse the contents of HTML codes, for exemple.