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

wesley chun wescpy at gmail.com
Sat Jul 23 21:13:46 CEST 2011


i forgot to define these:

str() - printable/human-readable string representation of an object
repr() - evaluatable string representation of an object (can "eval()"
it, meaning it is a string representation that evaluates to a Python
object)

in other words:

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

eval(str(x)) is not a valid Python object (you'll get a NameError)
while eval(repr(x)) *is* a valid Python object (you'll get a string
'foo'):

>>> eval('foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'foo' is not defined
>>> eval("'foo'")
'foo'

-wesley


On Sat, Jul 23, 2011 at 12:06 PM, wesley chun <wescpy at gmail.com> wrote:
> %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?


-- 
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Python Web Development with Django", Addison Wesley, (c) 2009
    http://withdjango.com

wesley.chun : wescpy-gmail.com : @wescpy
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list