gpt4 book ai didi

python - %r 是什么意思?

转载 作者:IT老高 更新时间:2023-10-28 20:21:00 28 4
gpt4 key购买 nike

下面语句中的%r是什么意思?

print '%r' % (1)

我想我听说过 %s%d%f,但从未听说过。

最佳答案

背景:

在 Python 中,有两个内置函数可以将对象转换为字符串:strrepr . str 应该是一个友好的、人类可读的字符串。 repr 应该包含有关对象内容的详细信息(有时,它们会返回相同的内容,例如整数)。按照惯例,如果有一个 Python 表达式将评估另一个对象 ==,repr 将返回这样的表达式,例如

>>> print repr('hi')'hi'  # notice the quotes here as opposed to...>>> print str('hi')hi

If returning an expression doesn't make sense for an object, repr should return a string that's surrounded by < and > symbols e.g. <blah>.

To answer your original question:

%s <-> str
%r <-> repr

In addition:

You can control the way an instance of your own classes convert to strings by implementing __str__ and __repr__ methods.

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

关于python - %r 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2354329/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com