Python Field Widths

Field Widths

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



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


Save as "014.t".

Lastly, create a pyramid using "/", "\\" (you must use the double slash for the right side or you will get an error - it will only print one of the slashes - try it and see!) for the sides, "^" for the top and "_" underscores for the bottom using field widths.
Remember, it has to be written with only one character per line of code.
See if you can make it better!
Image and video hosting by TinyPic

Finally, create a smiley face using any character you feel.  Remember, the most important part is that you cannot place a full line of print "%s" % "-------------" - it must be a separate character for each line of code.