python中%s和%r的区别

 1 %r用rper()方法处理对象
 2 
 3 %s用str()方法处理对象
 4 
 5 有些情况下,两者处理的结果是一样的,比如说处理int型对象。
 6 
 7 例一:
 8 
 9 [python] view plain copy 在CODE上查看代码片派生到我的代码片
10 print "I am %d years old." % 22  
11 print "I am %s years old." % 22  
12 print "I am %r years old." % 22  
13 
14 返回结果:
15 [python] view plain copy 在CODE上查看代码片派生到我的代码片
16 I am 22 years old.  
17 I am 22 years old.  
18 I am 22 years old.  
19 
20 另外一些情况两者就不同了
21 例二:
22 
23 [python] view plain copy 在CODE上查看代码片派生到我的代码片
24 text = "I am %d years old." % 22  
25 print "I said: %s." % text  
26 print "I said: %r." % text  
27 
28 返回结果:
29 [python] view plain copy 在CODE上查看代码片派生到我的代码片
30 I said: I am 22 years old..  
31 I said: 'I am 22 years old.'. // %r 给字符串加了单引号  
32 
33 再看一种情况
34 例三:
35 
36 [python] view plain copy 在CODE上查看代码片派生到我的代码片
37 import datetime  
38 d = datetime.date.today()  
39 print "%s" % d  
40 print "%r" % d  
41 
42 
43 返回结果:
44 [python] view plain copy 在CODE上查看代码片派生到我的代码片
45 2014-04-14  
46 datetime.date(2014, 4, 14)  
47 
48 可见,%r打印时能够重现它所代表的对象(rper() unambiguously recreate the object it represents)
原文地址:https://www.cnblogs.com/chengyunshen/p/7196257.html