2015-10-26 23 views
5
>>>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' 

Io uso solo %r(repr()) in python2 e dovrebbe funzionare in python3.5. Perché è?formato r (repr) di stampa in python3

Inoltre, quale formato dovrei usare?

risposta

6

Quello che stai cercando si chiama flag di conversione. E che dovrebbe essere specificato come questo

>>> print('you say:{0!r}'.format("i love you")) 
you say:'i love you' 

Citando Python 3 di official documentation,

Tre bandierine di conversione sono attualmente supportate: '!s' che chiede str() sul valore, '!r' che chiama repr() e '!a' che chiama ascii().

prega di notare che, Python 2 supporta solo !s e !r. Come per

Due flag di conversione del official documentation, Python 2 sono correntemente supportati: '!s' che invita str() sul valore, e '!r' che chiama repr().


In Python 2, si potrebbe avere fatto qualcosa di simile

>>> 'you say: %r' % "i love you" 
"you say: 'i love you'" 

Ma anche in Python 2 (anche in Python 3), è possibile scrivere la stessa cosa con !r con format, come questo

>>> 'you say: {!r}'.format("i love you") 
"you say: 'i love you'" 

Citando esempio da official documentation,

Sostituzione %s e %r:

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

@wim Impossibile trovare il rilascio effettivo ha ottenuto introdotto, ma come per la documentazione è disponibile dal v3.2 – thefourtheye