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

PythonProgramming

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.

raja
Published on 18-Apr-2018 11:45:12
Advertisements