在 python3 中打印的格式 r(repr)

format r(repr) of print in python3

>>>print('You say:{0:r}'.format("i love you"))
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    print('You say:{0:r}'.format("i love you"))
ValueError: Unknown format code 'r' for object of type 'str'

我只是在 python2 中使用 %r(repr()),它应该在 python3.5 中有效。为什么会这样?

此外,我应该使用什么格式?

您要找的是转换标志。应该这样指定

>>> print('you say:{0!r}'.format("i love you"))
you say:'i love you'

引用 Python 3 的 official documentation,

Three conversion flags are currently supported: '!s' which calls str() on the value, '!r' which calls repr() and '!a' which calls ascii().

请注意,Python 2 仅支持 !s!r。根据 Python 2 的 official documentation,

Two conversion flags are currently supported: '!s' which calls str() on the value, and '!r' which calls repr().


在 Python 2 中,您可能做过类似

的事情
>>> 'you say: %r' % "i love you"
"you say: 'i love you'"

但即使在 Python 2 中(也在 Python 3 中),你也可以用 !rformat 写同样的东西,像这样

>>> 'you say: {!r}'.format("i love you")
"you say: 'i love you'"

引用来自 official documentation

的示例

Replacing %s and %r:

>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
"repr() shows quotes: 'test1'; str() doesn't: test2"

在python3的f字符串格式化中,您还可以使用:

print(f"You say:{'i love you'!r}")
You say:'i love you'
print(f'You say:{"i love you"!r}')
You say:'i love you'

注意到 return 'i love you' 都用单引号括起来。