Python中%r和%s的詳解
%r用rper()方法處理對象
%s用str()方法處理對象
有些情況下,兩者處理的結(jié)果是一樣的,比如說處理int型對象。
例一:
1
2
3
|
print "I am %d years old." % 22 print "I am %s years old." % 22 print "I am %r years old." % 22 |
返回結(jié)果:
1
2
3
|
I am 22 years old. I am 22 years old. I am 22 years old. |
另外一些情況兩者就不同了
例二:
1
2
3
|
text = "I am %d years old." % 22 print "I said: %s." % text print "I said: %r." % text |
返回結(jié)果:
1
2
|
I said: I am 22 years old.. I said: 'I am 22 years old.' . / / % r 給字符串加了單引號 |
再看一種情況
例三:
1
2
3
4
|
import datetime d = datetime.date.today() print "%s" % d print "%r" % d |
返回結(jié)果:
1
2
|
2014 - 04 - 14 datetime.date( 2014 , 4 , 14 ) |
可見,%r打印時能夠重現(xiàn)它所代表的對象(rper() unambiguously recreate the object it represents)
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!