%r用rper()方法處理對象github
%s用str()方法處理對象spa
有些狀況下,二者處理的結果是同樣的,好比說處理int型對象。.net
例一:code
- 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 給字符串加了單引號
再看一種狀況
例三:blog
- 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-pythonip