python中%r和%s的区别

%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 给字符串加了单引号  

再看一种情况
例三:
>> from datetime import datetime 
>> timeinfo = datetime.today()

>> timeinfo
datetime.datetime(2016, 6, 7, 21, 17, 34, 925488)
>> type(timeinfo)
datetime.datetime

>> repr(timeinfo)
'datetime.datetime(2016, 6, 7, 21, 17, 34, 925488)'
>> str(timeinfo)
'2016-06-07 21:17:34.925488'

%r会将后面给的参数原样打印出来,带有类型信息。
formatter = "%r %r %r %r"
 
print formatter % (1, 2, 3, 4)
print formatter % ("one", "two", "three", "four")
print formatter % (True, False, False, True)
print formatter % (formatter, formatter, formatter, formatter)
print formatter % (
"I had this thing.",
"That you could type up right.",
 "But it didn't sing.",
 "So I said goodnight."
 )

输出结果:

$ python ex8.py
1 2 3 4
'one' 'two' 'three' 'four'
True False False True
'%r %r %r %r' '%r %r %r %r' '%r %r %r %r' '%r %r %r %r'
'I had this thing.' 'That you could type up right.' "But it didn't sing." 'So I said goodnight.'
$
posted @ 2018-01-02 20:09  xushukui  阅读(1031)  评论(0编辑  收藏  举报