>>>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?
In, Python %s and %d are used for formatting strings. %s acts a placeholder for a string while %d acts as a placeholder for a number. Their associated values are passed in via a tuple using the % operator.
Method 2: Formatting string using format() method Format() method was introduced with Python3 for handling complex string formatting more efficiently. Formatters work by putting in one or more replacement fields and placeholders defined by a pair of curly braces { } into a string and calling the str. format().
There are several ways to format output. To use formatted string literals, begin a string with f or F before the opening quotation mark or triple quotation mark. Inside this string, you can write a Python expression between { and } characters that can refer to variables or literal values.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With