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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The
%sspecifier converts the object usingstr(), and%rconverts it usingrepr().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:
Types for which
repr()doesn’t produce Python syntax include those that point to external resources such as afile, which you can’t guarantee to recreate in a different context.