python中%s和%r


%r用rper()方法處理對象

%s用str()方法處理對象

有些情況下,兩者處理的結果是一樣的,比如說處理int型對象。

例子1:

In [1]: print 'I am %d years old.' % 25 I am 25 years old. In [2]: print 'I am %s years old.' % 25 I am 25 years old. In [3]: print 'I am %r years old.' % 25 I am 25 years old.

 

另外一些情況兩者就不同了 : 
例子2:

In [4]: text = ' I am %d years old.' % 25 In [5]: print 'I said: %s.' % text I said: I am 25 years old.. In [6]: print 'I said: %r.' % text I said: ' I am 25 years old.'. #輸出帶了單引號。

 

例子3:

In [7]: import datetime In [8]: d = datetime.date.today() In [9]: print '%s' % d 2017-02-17 In [10]: print '%r' % d datetime.date(2017, 2, 17)

 

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

來自:http://blog.csdn.net/wusuopubupt/article/details/23678291


免責聲明!

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



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