python - !r 在 str() 和 repr() 中做了什么?

根据Python 2.7.12 documentation :

!s (apply str()) and !r (apply repr()) can be used to convert the value before it is formatted.

>>> import math
>>> print 'The value of PI is approximately {}.'.format(math.pi)
The value of PI is approximately 3.14159265359.
>>> print 'The value of PI is approximately {!r}.'.format(math.pi)
The value of PI is approximately 3.141592653589793.

有趣的是,转换后的值是repr()的输出,而不是str()

>>> str(math.pi)
'3.14159265359'
>>> repr(math.pi)
'3.141592653589793'

那么这里的“转换值”是什么意思呢?让它不那么可读?

最佳答案

为了将某些东西in格式化为字符串,必须首先创建该东西的字符串表示。 “转换值”基本上是在谈论如何构造字符串表示。在 python 中,有两种相当自然的选择来获得某事物的字符串表示... strrepr . str通常更人性化一点,repr一般比较精确。也许 official documentation是寻找差异的最佳去处:

object.__repr__(self)

  • Called by the repr() built-in function to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form <...some useful description...> should be returned. The return value must be a string object. If a class defines __repr__() but not __str__(), then __repr__() is also used when an “informal” string representation of instances of that class is required.

  • This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.

object.__str__(self)

  • Called by str(object) and the built-in functions format() and print() to compute the “informal” or nicely printable string representation of an object. The return value must be a string object.

  • This method differs from object.__repr__() in that there is no expectation that __str__() return a valid Python expression: a more convenient or concise representation can be used.

  • The default implementation defined by the built-in type object calls object.__repr__().

str.format , !s选择使用str格式化对象而 !r选择repr格式化值。

使用字符串可以很容易地看出区别(因为 repr 字符串将包含外引号)。:

>>> 'foo {}'.format('bar')
'foo bar'
>>> 'foo {!r}'.format('bar')
"foo 'bar'"

这两种方法之间的区别在很大程度上取决于被格式化的对象。对于许多对象(例如那些不覆盖 __str__ 方法的对象),格式化输出不会有任何差异。

https://stackoverflow.com/questions/38418070/

相关文章:

java - 内置字符串格式与字符串连接作为日志记录参数

formatting - printf, sprintf 至少打印两位小数

php - 如何创建友好的日期格式(例如 "submitted 2 days ago")

javascript - 在格式化数字输入时验证数字输入

postgresql - 如何为 PostgreSQL 设置千位分隔符?

formatting - Fortran 中带有前导零的格式化输出

c# - 在 Visual Studio 201x 中关闭 #region 的自动格式化

javascript - 如何更改 winston 日志格式?

ide - 保存文件时禁用重新格式化代码

linux - 使用 *nix 中的 column 命令格式化列表