", line 1...">

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?

+5
source share
1 answer

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

Note that Python 2 only supports !s and !r According to the official Python 2 documentation ,

Two conversion flags are currently supported: '!s' , which calls str() for the value, and '!r' , which calls repr() .


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 %s and %r :

 >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2') "repr() shows quotes: 'test1'; str() doesn't: test2" 
+7
source

Source: https://habr.com/ru/post/1234497/


All Articles