R (repr) format for printing 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' I just use %r(repr()) in python2 and it should work in python3.5. Why?
Also, what format should I use?
What you are looking for is called a conversion flag. And it should be indicated as
>>> print('you say:{0!r}'.format("i love you")) you say:'i love you' Quoting Python 3 official documentation ,
Currently, three conversion flags are supported:
'!s', which callsstr()for the value'!r', which callsrepr()and'!a', which callsascii().
Note that Python 2 only supports !s and !r According to the official Python 2 documentation ,
Two conversion flags are currently supported:
'!s', which callsstr()for the value, and'!r', which callsrepr().
In Python 2, you could do 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 thing with !r using format like this
>>> 'you say: {!r}'.format("i love you") "you say: 'i love you'" Sample quote from the official documentation ,
Replacing
%sand%r:>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2') "repr() shows quotes: 'test1'; str() doesn't: test2"