2016-05-16 4 views
2

Dies ist möglicherweise die einfachste Frage. Aber ich habe versucht, die einzelnen Werte des Tupels in der folgenden Weise zu drucken.Drucken formatierte Tupelwerte

mytuple=('new','lets python','python 2.7') 

>>> print "%{0} experience, %{1} with %{2} " %mytuple 
Traceback (most recent call last): 
    File "<pyshell#25>", line 1, in <module> 
    print "%{0} experience, %{1} with %{2} " %mytuple 
ValueError: unsupported format character '{' (0x7b) at index 1 

Ich möchte den Ausgang wie folgt drucken.

"new experience, lets python with python 2.7" 

Ich erinnere mich nicht, wo es gemacht wurde. Wird es Tample-Werte entpacken, formatierte Tupel drucken.

+0

verwenden Sie sowohl die '%' Methode und Wählen Sie mit der '{}' .format-Methode einen aus und bleiben Sie dabei. –

+0

Aye! Danke @ TadhgMcDonald-Jensen, es funktioniert ganz gut. Ich habe unnötige Klammern hinzugefügt, wenn sie nicht benötigt wurden. Das lief auf Fehler hinaus. –

Antwort

5

Statt printf -Stil Formatierung und str.format des Mischens, wählen Sie eine:

printf-style formatting:

>>> mytuple = ('new','lets python','python 2.7') 
>>> print "%s experience, %s with %s" % mytuple 
new experience, lets python with python 2.7 

str.format:

>>> print "{0} experience, {1} with {2}".format(*mytuple) 
new experience, lets python with python 2.7 
1

Sie Format-Methode verwenden, und Sternchen, das Problem zu lösen .

entnehmen Sie bitte this link für weitere Details

>>mytuple=('new','lets python','python 2.7') 
>>print "{0} experience, {1} with {2} ".format(*mytuple) 
new experience, lets python with python 2.7 
1

Sie können jeden der Methode. Das Format ist jedoch einfacher und Sie können es einfacher verwalten.

>>> a = '{0} HI {1}, Wassup {2}' 
>>> a.format('a', 'b', 'c') 
'a HI b, Wassup c' 
>>> b = ('a' , 'f', 'g') 
>>> a.format(*b) 
'a HI f, Wassup g' 
1

Sie gemischt gerade printf und str.format up, benötigen Sie einen von ihnen wählen:

>>> tuple1 = ("hello", "world", "helloworld") 
>>> print("%s, %s, %s" % tuple1) 

oder:

>>> tuple1 = ("hello", "world", "helloworld") 
>>> print("{}, {}, {}".format(*tuple1)) 
0

nur ein wenig ändern müssen:

>>> mytuple=('new','lets python','python 2.7') 
>>> print "%s experience, %s with %s " %mytuple 
new experience, lets python with python 2.7 
>>>