Preparation

To print strings in accordance with a very precise description of the layout, you can use the str.format() method in Python. This method can be called directly on a format string: formatstring.format(values). The formatstring is a string that contains so-called replacement fields, which are indicated by curly braces {}. The fields are replaced with arguments in the values in order. You can number the fields starting from 0 by putting the numbers between the curly braces. You can also reference fields by a name, which is put between the curly braces. In the values you can then use name=value (these pairs have to be the first arguments in the values). Inside the curly braces you can also put format specification by using : followed by certain characters to denote the format, in about the same way as you would use the % operator.

For example, the format specification {:s} indicates that a string must be placed in that position and the layout specification {:3d} indicates that an integer must be placed, lined out over 3 positions (completed by spaces on the left). The layout can be described with even more detail: the layout specification {:7.3f} for example, indicates that a floating point number must be written out with 3 digits after the comma, outlined on the right over 7 positions. For further expansions and details we refer to the text book (page 196, 4.4 formatted output for strings) or to the online Python manual1. The example below illustrates the layout specifications that were described above.

>>> print('>>>{:s}<<<'.format('spam'))
>>>spam<<<
>>> print('>>>{:3d}<<<'.format(42))
>>> 42<<<
>>> print('>>>{:7.3f}<<<'.format(3.14))
>>>  3.140<<<
>>> print('{:s}\t{:d}\t{:5.3f}'.format('spam', 42, 3.14))
spam    42      3.140

Assignment

Write a program that prints the following multiplication grid:

      1   2   3   4   5   6   7   8   9  10  11  12
  1   1   2   3   4   5   6   7   8   9  10  11  12
  2   2   4   6   8  10  12  14  16  18  20  22  24
  3   3   6   9  12  15  18  21  24  27  30  33  36
  4   4   8  12  16  20  24  28  32  36  40  44  48
  5   5  10  15  20  25  30  35  40  45  50  55  60
  6   6  12  18  24  30  36  42  48  54  60  66  72
  7   7  14  21  28  35  42  49  56  63  70  77  84
  8   8  16  24  32  40  48  56  64  72  80  88  96
  9   9  18  27  36  45  54  63  72  81  90  99 108
 10  10  20  30  40  50  60  70  80  90 100 110 120
 11  11  22  33  44  55  66  77  88  99 110 121 132
 12  12  24  36  48  60  72  84  96 108 120 132 144

Add enough spaces, so that all columns are exactly 3 digits wide and are separated by a column that is one space wide.