python中%r和%s的区别

来源:互联网 发布:淘宝秒杀有人抢到了吗 编辑:程序博客网 时间:2024/04/27 13:22

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

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

有些情况下,两者处理的结果是一样的,比如说处理int型对象。

例一:

[python] view plain copy
  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
  1. I am 22 years old.  
  2. I am 22 years old.  
  3. I am 22 years old.  

另外一些情况两者就不同了

例二:

[python] view plain copy
  1. text = "I am %d years old." % 22  
  2. print "I said: %s." % text  
  3. print "I said: %r." % text  

返回结果:

[python] view plain copy
  1. I said: I am 22 years old..  
  2. I said: 'I am 22 years old.'. // %r 给字符串加了单引号  

再看一种情况

例三:

[python] view plain copy
  1. import datetime  
  2. d = datetime.date.today()  
  3. print "%s" % d  
  4. print "%r" % d  


返回结果:
[python] view plain copy
  1. 2014-04-14  
  2. datetime.date(2014414)  

可见,%r打印时能够重现它所代表的对象(rper() unambiguously recreate the object it represents)


参考:http://stackoverflow.com/questions/6005159/when-to-use-r-instead-of-s-in-python

0 0
原创粉丝点击