在 Learn Python the Hard Way 第21页中,我看到了这个代码示例:
x = "There are %d types of people." % 10
...
print "I said: %r." % x
为什么这里使用%r
而不是%s
? 你什么时候会使用%r
,什么时候使用%s
?
在 Learn Python the Hard Way 第21页中,我看到了这个代码示例:
x = "There are %d types of people." % 10
...
print "I said: %r." % x
为什么这里使用%r
而不是%s
? 你什么时候会使用%r
,什么时候使用%s
?
%s
格式说明符使用str()
将对象转换为字符串,%r
则使用repr()
进行转换。
对于一些对象,如整数,它们产生相同的结果,但是repr()
有一个特殊之处(对于可以这样做的类型),即它通常返回一个有效的Python语法结果,可以用于无歧义地重新创建所表示的对象。
以下是一个示例,使用日期:
>>> import datetime
>>> d = datetime.date.today()
>>> str(d)
'2011-05-14'
>>> repr(d)
'datetime.date(2011, 5, 14)'
repr()
无法生成 Python 语法的类型包括指向外部资源的类型,例如 file
,你不能保证在不同的上下文中重新创建这些资源。
使用%r
进行调试,因为它显示变量的“原始”数据,但其他格式用于向用户显示。
这就是%r
格式化的工作方式;它以你编写的方式打印(或接近)。它是用于调试的“原始”格式。在此处,用于向用户显示的\n
无法正常工作。%r
显示变量的原始数据表示。
months = "\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
print "Here are the months: %r" % months
输出:
Here are the months: '\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug'
请参考Learn Python the Hard Way中的这个例子。
%r
带有引号:
它的结果会像这样:
I said: 'There are 10 types of people.'.
如果你使用了%s
,它就会变成:
I said: There are 10 types of people..
>>> import datetime
>>> x = datetime.date.today()
>>> print x
2013-01-11
>>>
>>>
>>> print "Today's date is %s ..." % x
Today's date is 2013-01-11 ...
>>>
>>> print "Today's date is %r ..." % x
Today's date is datetime.date(2013, 1, 11) ...
>>>
当我运行这段代码时,它帮助我看到了 %r 的有用性。
%r
和%s
占位符打印输出的示例,以便用户可以更清楚地看到它们之间的区别。 - amanuel2