Python 中的 str() 与 repr()?

pythonserver side programmingprogramming更新于 2025/8/2 20:28:17

Python 中的 str() 和 repr() 方法均用于字符串的字符串表示。虽然它们似乎服务于相同的目的,但它们之间还是有一点区别的。

您是否注意到当您调用 Python 内置函数 str(x) 时会发生什么,其中 x 是您想要的任何对象?str(x) 的返回值取决于两种方法:__str__ 是默认选择,__repr__ 是后备。

让我们首先看看 Python 文档对它们的介绍 −

>>> help(str)
Help on class str in module builtins:

class str(object)
| str(object='') -> str
| str(bytes_or_buffer[, encoding[, errors]]) -> str
|
| Create a new string object from the given object.

>>> help(repr)
Help on built-in function repr in module builtins:

repr(obj, /)
Return the canonical string representation of the object.

For many object types, including most builtins, eval(repr(obj)) == obj.

现在让我们尝试通过几个例子来理解这两种方法

>>> str(123)
'123'
>>> repr(123)
'123'
>>> #Above we see- with integer data, there is no difference
>>> #Now let's try string data on these two methods
>>> str('Python')
'Python'
>>> repr('Python')
"'Python'"

对于整数值,repr() 和 str() 的返回值相同,但对于字符串的返回值有区别 - 一个是正式的,另一个是非正式的。

现在,如果您按照官方的 Python 文档进行操作 - __str__ 用于查找对象的“非正式”(可读)字符串表示,而 __repr__ 用于查找对象的“正式”字符串表示。

正式表示和非正式表示之间的区别在于,str 值的 __repr__ 的默认实现可以作为 eval 的参数调用,返回值将是一个有效的字符串对象。此函数 (repr()) 接受一个字符串并将其内容评估为 Python 代码。

因此,当我们将"'Python'"传递给它时,它就可以工作。但是,"Python"导致错误,因为它被解释为 Python 变量,而 Python 变量当然是未定义的。下面是理解它的代码 −

>>> x = "Python"
>>> repr(x)
"'Python'"
>>> x1 = eval (repr(x))
>>> x == x1
True

因此,如果我们尝试将 __str__ 的返回值作为 eval 的参数调用,则会失败。

>>> y = "Python"
>>> str(y)
'Python'
>>> y1 = eval(str(y))
Traceback (most recent call last):
File "<pyshell#51>", line 1, in <module>
y1 = eval(str(y))
File "<string>", line 1, in <module>
NameError: name 'Python' is not defined

另一个可以说明两者区别的例子是 −

>>> import datetime
>>> now = datetime.datetime.now()
>>> str(now)
'2019-03-29 01:29:23.211924'
>>> repr(now)
'datetime.datetime(2019, 3, 29, 1, 29, 23, 211924)'

在上面的输出中,str(now) 计算一个包含 now 值的字符串,而 repr(now) 再次返回重建 now 对象所需的 python 代码。

主要区别

str()
repr()
使对象可读
重现对象的必需代码
生成输出给最终用户
生成输出给开发人员

在为您的类编写 __str__ 和 __repr__ 时需要考虑以上几点。


相关文章


有用资源