python中%r和%s的區別


%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(2014, 4, 14)  


可見,%r打印時能夠重現它所代表的對象(rper() unambiguously recreate the object it represents)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM