Details and differences of % r and % s in Python, and details of python % r % s
Explanation of % r and % s in Python
% R uses the rper () method to process objects
% S use the str () method to process objects
In some cases, the two processes the same result, for example, processing an int-type object.
Example 1:
print "I am %d years old." % 22 print "I am %s years old." % 22 print "I am %r years old." % 22
Returned results:
I am 22 years old. I am 22 years old. I am 22 years old.
In other cases, the two are different.
Example 2:
text = "I am %d years old." % 22 print "I said: %s." % text print "I said: %r." % text
Returned results:
I said: I am 22 years old .. I said: 'I am 22 years old.'. // % r adds single quotes to the string
Let's look at another situation.
Example 3:
import datetime d = datetime.date.today() print "%s" % d print "%r" % d
Returned results:
2014-04-14 datetime.date(2014, 4, 14)
It can be seen that % r can reproduce the object it represents when printing (rper () unambiguously recreate the object it represents)
Thank you for reading this article. I hope it will help you. Thank you for your support for this site!