Tuples and the print Statement

A Byte of Python 

Go to the Table of Contents. Visit the Gifcom web site.

One of the most common usage of tuples is with the print statement. Here is an example:

Example 9.3. Output using tuples

# Filename: print_tuple.py

age = 22
name = 'Swaroop'

print '%s is %d years old' % (name, age)
print 'Why is %s playing with that python?' % name


$ python print_tuple.py
Swaroop is 22 years old
Why is Swaroop playing with that python?

How It Works

The print statement can take a string using certain specifications followed by the % symbol followed by a tuple of items matching the specification. The specifications are used to format the output in a certain way. The specification can be like %s for strings and %d for integers. The tuple must have items corresponding to these specifications in the same order.

Observe the first usage where we use %s first and this corresponds to the variable name which is the first item in the tuple and the second specification is %d corresponding to age which is the second item in the tuple.

What Python does here is that it converts each item in the tuple into a string and substitutes that string value into the place of the specification. Therefore the %s is replaced by the value of the variable name and so on.

This usage of the print statement makes writing output extremely easy and avoids lot of string manipulation to achieve the same. It also avoids using commas everywhere as we have done till now.

Most of the time, you can just use the %s specification and let Python take care of the rest for you. This works even for numbers. However, you may want to give the correct specifications since this adds one level of checking that your program is correct.

In the second print statement, we are using a single specification followed by the % symbol followed by a single item - there are no pair of parentheses. This works only in the case where there is a single specification in the string.