So I have this code:
formatter = "%r %r %r %r"
print formatter % (1, 2, 3, 4)
print formatter % ("one", "two", "three", "four")
And I get this output:
1 2 3 4
‘one’ ‘two’ ‘three’ ‘four’
My question is:
Why does the second line of output have single quotes around it? I’m not quite sure how the %r conversion type really works.
When I change the code to:
formatter = "%r %r %r %r"
print formatter % (1, 2, 3, 4)
print "%s %s %s %s" % ("one", "two", "three", "four")
I get this result:
1 2 3 4
one two three four
I just don’t understand why they work differently. Can someone break it down for me?
I’ve read:
With the expression
'abc%rdef' % obj, the part'%r'is replaced withrepr(obj)With the expression
'ABC%sDEF' % obj, the part'%s'is replaced withstr(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:
.
if you consider the list defined by
li = [12,45,'haze']print liwill 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 valueif you consider the string defined by
ss = 'oregon':print sswill print oregon , without any quote aroundprint 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.