Annapoornima Koppad Annapoornima Koppad - 6 months ago 19
Python Question

Printing formatted tuple values

This may be the simplest of questions. But I tried to print the individual values of the tuple in the following manner.

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


I want to print the output to be like the following.

"new experience, lets python with python 2.7"


I don't remember where it was it done. Is it called unpacking tuple values, printing formatted tuples.

Answer

Instead of mixing printf-style formating and str.format, choose one:

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