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

Wayne Werner waynejwerner at gmail.com
Sat Jul 23 15:27:27 CEST 2011


On Sat, Jul 23, 2011 at 7: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 ?
> <snip>


As the answer here (
http://stackoverflow.com/questions/6005159/when-to-use-r-instead-of-s-in-python)
says,  it changes the method of evaluating an object. Here's a simple
example:


In [2]: class Thingy:
   ...:     def __str__(self):
   ...:         return "Hello"
   ...:     def __repr__(self):
   ...:         return "Goodbye"
   ...:
   ...:

In [3]: "%s %r" % (Thingy(), Thingy())
Out[3]: 'Hello Goodbye'

I'm not sure if there's a huge difference, and to be honest usually my
classes look like this:

class CoolGuy:
    def __str__(self):
        return "I'm a cool guy"
    def __repr__(self):
        return str(self)

so there would be no difference between the two.

In the interpreter,  the __repr__ method is called on the class when you
type it in - that's how python knows what to display:

In [5]: cool = Thingy()

In [6]: cool
Out[6]: Goodbye

Classes also start out with a default __repr__ that contains... well, this:

 In [7]: class AnotherThingy:
   ...:     pass
   ...:

In [8]: neat = AnotherThingy()

In [9]: neat
Out[9]: <__main__.AnotherThingy instance at 0x9a5a66c>


HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110723/1df6a358/attachment.html>


More information about the Tutor mailing list