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

wesley chun wescpy at gmail.com
Sat Jul 23 21:06:11 CEST 2011


%s = send object to str() first then drop it into the string
%r = send object to repr() first then drop it into the string

pretty straightforward:

>>> x = 'foo'
>>> str(x)
'foo'
>>> repr(x)
"'foo'"

why do people do %r at all? to get the quotes for free: :-)

>>> x = 'Python'
>>> print "What is this '%s' language?" % x
What is this 'Python' language?
>>> print "What is this %r language?" % x
What is this 'Python' language?

cheers,
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python", Prentice Hall, (c)2007,2001
"Python Fundamentals", Prentice Hall, (c)2009
    http://corepython.com

wesley.chun : wescpy-gmail.com : @wescpy
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110723/f0a016fa/attachment.html>


More information about the Tutor mailing list