Beginner Python Question RE: String Formatting Type and repr() function
-
15-01-2021 - |
Question
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:
Solution
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.
OTHER TIPS
%s
tell's python to call the str()
function on each element of your tuple. %r
tell's python to call the repr()
function on each element of your tuple.
By the docs:
Return a string containing a nicely printable representation of an object. For strings, this returns the string itself.
Return a string containing a printable representation of an object.
This means, if the object you call repr()
on is a string object (in python everything is an object) it shows you how the different characters are represented.
@your specific question: I assume that the "..." indicate, that it is a string. If you call repr() on an int there are no "...".