Printing tuple with string formatting in Python


So, i have this problem. I got tuple (1,2,3) which i should print with string formatting. eg.

tup = (1,2,3)
print "this is a tuple %something" % (tup)

and this should print tuple representation with brackets, like

This is a tuple (1,2,3)

But I get TypeError: not all arguments converted during string formatting instead.

How in the world am I able to do this? Kinda lost here so if you guys could point me to a right direction :)

9/17/2014 9:09:35 PM

Accepted Answer

>>> thetuple = (1, 2, 3)
>>> print "this is a tuple: %s" % (thetuple,)
this is a tuple: (1, 2, 3)

Making a singleton tuple with the tuple of interest as the only item, i.e. the (thetuple,) part, is the key bit here.

9/21/2009 5:07:07 PM

Note that the % syntax is obsolete. Use str.format, which is simpler and more readable:

t = 1,2,3
print 'This is a tuple {0}'.format(t)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow