Field Widths

THIS PAGE NEEDS TO BE UPDATED FOR PYTHON 3!

A field width specification can be included to tell Python how much space you want something to use when printed on the screen. This is useful when you are printing columns of data or information, such as on a sales receipt. For example:

# prints the first line

print "%12s" % "Item",

print "%12s" % "Quantity",

print "%12s" % "Cost",

print "%12s" % "Total"

# prints the second line

print "%12s" % "Apples",

print "%12s" % "3",

print "%12s" % "0.75",

print "%12s" % "2.25"

...prints the following:

Note that this example uses quoted "strings" for the printed text. If you were to print numbers (or calculated numbers) you would use "d" for integer numbers (such as 10, 998, or 10567) or "f" for real numbers such as 1.12, 10.98, or 987.176, as this example below demonstrates:

Also note that real numbers are padded with trailing zeroes. To designate the number of decimal places in a real number, add a decimal to the field width, such as "%12.2".

This example demonstrates the use of field width with numbers:

print "%10d" % 198

print "%10.2f" % 198

print "%10f" % 209.87

...produces:

Assignment

Create a neatly-spaced "times table" from 12 x 1 to 12 x 12 that uses field widths. Use formulas to calculate the products.

Save as "014.t".