python中s%和r%的区别

转载自http://blog.csdn.net/wusuopubupt/article/details/23678291python

%r用rper()方法处理对象github

%s用str()方法处理对象spa

有些状况下,二者处理的结果是同样的,好比说处理int型对象。.net

例一:code

 

[python]  view plain  copy
 
 在CODE上查看代码片派生到个人代码片
  1. print "I am %d years old." % 22  
  2. print "I am %s years old." % 22  
  3. print "I am %r years old." % 22  

返回结果:

 

 

[python]  view plain  copy
 
 在CODE上查看代码片派生到个人代码片
  1. I am 22 years old.  
  2. I am 22 years old.  
  3. I am 22 years old.  

另一些状况二者就不一样了

 

例二:对象

 

[python]  view plain  copy
 
 在CODE上查看代码片派生到个人代码片
  1. text = "I am %d years old." % 22  
  2. print "I said: %s." % text  
  3. print "I said: %r." % text  

返回结果:

 

 

[python]  view plain  copy
 
 在CODE上查看代码片派生到个人代码片
  1. I said: I am 22 years old..  
  2. I said: 'I am 22 years old.'. // %r 给字符串加了单引号  

再看一种状况

 

例三:blog

 

[python]  view plain  copy
 
 在CODE上查看代码片派生到个人代码片
  1. import datetime  
  2. d = datetime.date.today()  
  3. print "%s" % d  
  4. print "%r" % d  

 

 

返回结果:
[python]  view plain  copy
 
 在CODE上查看代码片派生到个人代码片
  1. 2014-04-14  
  2. 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

相关文章
相关标签/搜索