One - One Code All

Blog Content

python格式化输出 %r 与 %s 的区别(__repr__ 与 __str__)

Python   2009-03-22 23:15:46

在进行格式化输出时,%r 与 %s 的区别就好比 repr() 函数处理对象与 str() 函数处理对象的差别。

%s ⇒ str(),比较智能;
%r ⇒ repr(),处理较为简单和直接;

>> s = 'world'
>> print('hello %s'%s)
hello world
>> print('hello %r'%s)
hello 'world'

=======================
import datetime
t = datetime.date.today()
print '%r'%(t)
print '%s'%(t)

结果:

datetime.date(2015, 12, 11)
2015-12-11


上一篇:python中import语句的模块顺序
下一篇:python异常处理try-except Exception as e

The minute you think of giving up, think of the reason why you held on so long.