轉載自http://blog.csdn.net/wusuopubupt/article/details/23678291
版權聲明:https://github.com/wusuopubupt
%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)
參考:http://stackoverflow.com/questions/6005159/when-to-use-r-instead-of-s-in-python