根据Python 2.7.12 documentation :
!s
(applystr()
) and!r
(applyrepr()
) 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 中,有两种相当自然的选择来获得某事物的字符串表示... str
和 repr
. 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/