[Tutor] What's the difference between %s and %r?

Joel Goldstick joel.goldstick at gmail.com
Sat Jul 23 17:35:39 CEST 2011


On Sat, Jul 23, 2011 at 8:48 AM, amt <0101amt at gmail.com> wrote:

> Hello! I'm having troubles understanding what is the difference between %s
> and %r(format characters). I did google  and found something on
> StackOverflow but I don't understand the explanation as it's not beginner
> orientated.
>
>
> Also, I have this code from learn python the hard way. Why at line 9 does
> he uses %r? Why did he didn't wrote print "I said: %s." %x ?
>
> 1    x = "There are %d types of people." % 10
> 2    binary = "binary"
> 3    do_not = "don't"
> 4    y = "Those who know %s and those who %s." % (binary, do_not)
> 5
> 6    print x
> 7    print y
> 8
> 9    print "I said: %r." % x
> 10  print "I also said: '%s'." % y
> 11
> 12  hilarious = False
> 13  joke_evaluation = "Isn't that joke so funny?! %r"
> 14
> 15  print joke_evaluation % hilarious
> 16
> 17  w = "This is the left side of..."
> 18  e = "a string with a right side."
> 19
> 20  print w + e
>
>
>
> Thanks in advance!
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
r String (converts any python object using repr()). (5)

repr(*object*)¶ <http://docs.python.org/library/functions.html#repr>Return a
string containing a printable representation of an object. This is the same
value yielded by conversions (reverse quotes). It is sometimes useful to be
able to access this operation as an ordinary 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#eval>,
otherwise the representation is a string enclosed in angle brackets that
contains the name of the type of the object together with additional
information often including the name and address of the object. A class can
control what this function returns for its instances by defining a
__repr__() <http://docs.python.org/reference/datamodel.html#object.__repr__>method.I
did some checking.  %r runs the repr() function on the object.  In this case
x is a string that needs to be evaluated.  So print "I said: %r." % x first
evaluates x then creates the full string.


-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110723/951fea2d/attachment.html>


More information about the Tutor mailing list