%r用rper()方法处理对象
%s用str()方法处理对象
有些情况下,两者处理的结果是一样的,比如说处理int型对象。
例一:
print “I am %d years old.” % 22
print “I am %s years old.” % 22
print “I am %r years old.” % 22
返回结果:
I am 22 years old.
I am 22 years old.
I am 22 years old.
另外一些情况两者就不同了
例二:
text = “I am %d years old.” % 22
print “I said: %s.” % text
print “I said: %r.” % text
返回结果:
I said: I am 22 years old..
I said: ‘I am 22 years old.’. // %r 给字符串加了单引号
再看一种情况
例三:
import datetime
d = datetime.date.today()
print “%s” % d
print “%r” % d
返回结果:
2014-04-14
datetime.date(2014, 4, 14)
可见,%r打印时能够重现它所代表的对象(rper() unambiguously recreate the object it represents)
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/13848.html