>>>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'
I just use %r(repr())
in python2, and it should work in python3.5. Why is it?
Besides, what format should I use?
What you are looking for is called conversion flag. And that should be specified like this
>>> print('you say:{0!r}'.format("i love you"))
you say:'i love you'
Quoting Python 3's official documentation ,
Three conversion flags are currently supported:
'!s'
which callsstr()
on the value,'!r'
which callsrepr()
and'!a'
which callsascii()
.
Please note that, Python 2 supports only !s
and !r
. As per the Python 2's official documentation ,
Two conversion flags are currently supported:
'!s'
which callsstr()
on the value, and'!r'
which callsrepr()
.
In Python 2, you might have done something like
>>> 'you say: %r' % "i love you"
"you say: 'i love you'"
But even in Python 2 (also in Python 3), you can write the same with !r
with format
, like this
>>> 'you say: {!r}'.format("i love you")
"you say: 'i love you'"
Quoting example from 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"
In python3's f-string formatting, you can also use:
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'
Noted that both return 'i love you' enclosed in single-quotes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.