How do we format output so that we get it to look like we want it to? For example, how do we align output in columns? How do we control the number of decimal points that will be displayed? The basic scheme is as follows:
’ separates the format string from the ‘thing to be formatted’. In this example, the variable ‘a’ is what we want to format and print. Here is another example. print('%10s'%'Name', '%10s'%'Midterm' ,'%10s'%'Final','%10s'%'Average','%15s'%'Deviation') This will print the strings ‘Name’, ‘Midterm’, ‘Final’, ‘Average’, and ‘Deviation’.
In the conversion specifier, s indicates that a string will be printed, and 10 is how many spaces will be used. By default, the string will be “right adjusted” in the 10 spaces. The string ’Name’ is what will be printed. If we want it “left adjusted”, we would put a minus before the 10:’ %-10s’ Here is an example controlling the field width when printing floating point numbers. Here “10.3f” indicates a floating point number taking up 10 columns, and with 3 digits after the decimal point. Other conversion characters are d or i indicating an integer. “15.3f” means that 15 columns are used.