Doug Fir
Doug Fir

Reputation: 21212

Formatters %r and %s - difference in theory but this script says otherwise

I'm working through a Python tutorial that has repeatedly stated that %r is for debugging and is the raw representation whereas %s is the output.

But, consider this script from the tutorial:

age = raw_input("How old are you? ")
height = raw_input("What's your height? ")
weight = raw_input("What's your weight? ")

print "So, you're %r old, %r tall and %r heavy" % (age, height, weight)

And that function runs fine.

But when I changed each instance of %r to %s, there was no change in output? I'd like to state what I expected to see but I was not sure. I was expecting (hoping) to see something that illustrated the difference.

Can someone clarify?

Upvotes: 2

Views: 100

Answers (2)

mgilson
mgilson

Reputation: 309919

%r calls repr whereas %s calls str when formatting the string:

>>> class Foo(object):
...     def __str__(self):
...         return 'foo'
...     def __repr__(self):
...         return 'bar'
... 
>>> f = Foo()
>>> '%s' % f
'foo'
>>> '%r' % f
'bar'

For objects which define __repr__ and not __str__, the output will be the same, however, for strings, there is a difference (notably an extra quotation):

>>> print str('foo')
foo
>>> print repr('foo')
'foo'

Upvotes: 4

Matteo Italia
Matteo Italia

Reputation: 126787

Check better, there's quite of a difference:

>>> print "So, you're %r old, %r tall and %r heavy" % (age, height, weight)
So, you're '123' old, '456' tall and '789' heavy
>>> print "So, you're %s old, %s tall and %s heavy" % (age, height, weight)
So, you're 123 old, 456 tall and 789 heavy
>>> 

The single quotes are there in the first output since the "raw representation" of a string requires it (i.e., to put a string literal inside Python code you need to delimit it with single or double quotes), where in the second output they aren't printed, since you asked just to print the string as it is.

Upvotes: 3

Related Questions