On the same line type a space a space and a tuple that includes one data item for each formatting code in the string as shown here

4. print "%2s %5s %12s" % ('x', 'x**2', 'x**x')

The code prints the following results:

x

x**2

x**x

1

1

1

2

4

4

3

9

27

4

16

256

5

25

3125

It's easy to forget to use tuples when formatting with multiple data items. If you remember to do this consistently, you'll be ahead in the debugging game. Even experienced Python programmers make this mistake, so if you see an error message like this, you're in good company:

>>> '%s %s' % 'the', 'larch' Traceback (most recent call last):

File "<stdin>", line 1, in <module> TypeError: not enough arguments for format string

Here's the right way to do it:

>>> '%s %s' % ('the', 'larch') 'the larch'

Was this article helpful?

0 0

Post a comment