在 Python 中何时使用% r 而不是% s?

艰难学习 Python第21页,我看到了这个代码示例:

x = "There are %d types of people." % 10
...
print "I said: %r." % x

为什么在这里使用 %r而不是 %s? 你什么时候会使用 %r,什么时候会使用 %s

155980 次浏览

%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节目带引号:

就像这样:

I said: 'There are 10 types of people.'.

如果你使用的是 %s,它会是:

I said: There are 10 types of people..

以下是本•詹姆斯(Ben James)的回答,见上图:

>>> 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进行调试,因为它显示变量的“原始”数据, 而其他的则用于向用户显示。

这就是 %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'

从艰苦学习 Python 中检查 这个例子