>>>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'
我只是用 %r(repr())
在python2中,它应该在python3.5中工作。为什么会这样?
另外,我应该用什么格式?
你要找的是转换标志。它应该像这样指定
>>> print('you say:{0!r}'.format("i love you"))
you say:'i love you'
引用Python 3的 公文,
目前支持三种转换标志。
'!s'
它调用str()
值上。'!r'
其中调用repr()
和'!a'
其中调用ascii()
.
请注意,Python 2只支持 !s
和 !r
. 根据Python 2的 公文,
目前支持两个转换标志。
'!s'
调用str()
值上,以及'!r'
其中调用repr()
.
在Python 2中,您可能会做一些类似于
>>> 'you say: %r' % "i love you"
"you say: 'i love you'"
但即使在Python 2中(在Python 3中也一样),你也可以用 !r
与 format
,像这样
>>> 'you say: {!r}'.format("i love you")
"you say: 'i love you'"
引用以下例子 公文,
替换
%s
和%r
:>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2') "repr() shows quotes: 'test1'; str() doesn't: test2"
在python3的f-string格式中,你也可以使用。
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'
注意到两者都是用单引号返回 "我爱你"。