%r uses the rper() method to process objects
%s uses the str() method to process objects
The function str() is used to convert values into a form suitable for human reading. Repr() converts it into a form for the interpreter to read (if there is no equivalent syntax, a SyntaxError exception will occur). If an object does not have an interpretation form suitable for human reading, str() will return the equivalent of repr(). value. Many types, such as numerical values or structures such as linked lists and dictionaries, have a unified interpretation method for each function.
In some cases, the results of the two processes are the same, such as processing int objects.
Example 1:
print "I am %d years old." % 22 print "I am %s years old." % 22 print "I am %r years old." % 22
Return result:
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
Return result:
I said: I am 22 years old.. I said: 'I am 22 years old.'. #%r 给字符串加了单引号
Look at another situation
Example 3:
import datetime d = datetime.date.today() print "%s" % d print "%r" % d
Return result:
2017-08-16 datetime.date(2017, 8, 16)
It can be seen that %r can be reproduced when printing The object it represents (rper() unambiguously recreate the object it represents)
The above is the detailed content of Compare the usage differences between %r and %s in Python. For more information, please follow other related articles on the PHP Chinese website!