%r
以下陈述中的含义是什么?
print '%r' % (1)
Run Code Online (Sandbox Code Playgroud)
我想我已经听说过%s
,%d
和%f
,但从来没有听说过这一点.
all*_*ode 78
背景:
在Python中,有两个内置函数可以将对象转换为字符串:str
vs repr
. str
应该是一个友好的,人类可读的字符串.repr
应该包含有关对象内容的详细信息(有时,它们会返回相同的内容,例如整数).按照惯例,如果有一个Python表达式将eval到另一个==的对象,repr
将返回这样的表达式,例如
>>> print repr('hi') 'hi' # notice the quotes here as opposed to... >>> print str('hi') hi
如果返回表达式对于对象没有意义,repr
则应返回由<和>符号包围的字符串,例如<blah>
.
回答你原来的问题:
此外:
您可以通过实现__str__
和__repr__
方法来控制自己的类的实例转换为字符串的方式.
class Foo:
def __init__(self, foo):
self.foo = foo
def __eq__(self, other):
"""Implements ==."""
return self.foo == other.foo
def __repr__(self):
# if you eval the return value of this function,
# you'll get another Foo instance that's == to self
return "Foo(%r)" % self.foo
Run Code Online (Sandbox Code Playgroud)
小智 5
添加到上面给出的答复中,'%r'
在您拥有具有异构数据类型的列表的场景中会很有用。比方说,list = [1, 'apple' , 2 , 'r','banana']
在这种情况下,我们显然使用'%d'
or'%s'
会导致错误。相反,我们可以使用'%r'
打印所有这些值。