How to print a complete tuple in Python using string formatting?


When using the old style of string formatting in python, ie, "" % (), if the thing after the percent is a tuple, python tries to break it down and pass individual items in it to the string. For example,

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

This will give the output:

TypeError: not all arguments converted during string formatting

This is because of the reason mentioned above. If you want to pass a tuple, you need to create a wrapping tuple using the (tup, ) syntax. For example,

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

This will give the output:

this is a tuple (1, 2, 3)

The (tup,) notation differentiates a single-valued tuple from an expression.

Updated on: 17-Jun-2020

588 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements