Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

format r(repr) of print 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 is it?

Besides, what format should I use?

like image 468
Li haonan Avatar asked Oct 26 '15 02:10

Li haonan


People also ask

What is %s %d Python?

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.

How do I format a string in Python 3?

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().

How do I format a string to print in Python?

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.


1 Answers

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 calls str() on the value, '!r' which calls repr() and '!a' which calls ascii().

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 calls str() on the value, and '!r' which calls repr().


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"
like image 122
thefourtheye Avatar answered Sep 28 '22 09:09

thefourtheye