python3中的打印格式r(repr)

2024-06-17 13:40:36 发布

您现在位置:Python中文网/ 问答频道 /正文

>>>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中起作用。为什么?

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


Tags: inyouformatmostlinecallfilelast
1条回答
网友
1楼 · 发布于 2024-06-17 13:40:36

你要找的是转换标志。应该这样说明

>>> 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"

相关问题 更多 >