format r(repr) of print in python3
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.