Question
Asked By – coffee-grinder
On Learn Python the Hard Way page 21, I see this code example:
x = "There are %d types of people." % 10
...
print "I said: %r." % x
Why is %r
used here instead of %s
? When would you use %r
, and when would you use %s
?
Now we will see solution for issue: When to use %r instead of %s in Python? [duplicate]
Answer
The %s
specifier converts the object using str()
, and %r
converts it using repr()
.
For some objects such as integers, they yield the same result, but repr()
is special in that (for types where this is possible) it conventionally returns a result that is valid Python syntax, which could be used to unambiguously recreate the object it represents.
Here’s an example, using a date:
>>> import datetime
>>> d = datetime.date.today()
>>> str(d)
'2011-05-14'
>>> repr(d)
'datetime.date(2011, 5, 14)'
Types for which repr()
doesn’t produce Python syntax include those that point to external resources such as a file
, which you can’t guarantee to recreate in a different context.
This question is answered By – Ben James
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0