Basic Formatting in Python

advertisement

Introduction to Programming

Basic Formatting in Python

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:

<A string specifying the formatting>

%

<The ‘thing’ to be formatted>

Consider the following example.

The variable a is assigned 34.57, and this is printed when a is entered at the python prompt. Next a formatted expression is entered. Notice that there are two ‘%’ symbols. They have different meanings here. The second one (the one in black in the screenshot above) separates the two parts indicated above.

When we write ’%.1f’

%

a

‘%.1f’ is the <string specifying the formatting> part and a is <The ‘thing’ to be formatted>

Here is how it works.

We want to print out the value of the variable a, which is a floating point number. But, say we want to print it out with only one digit following the decimal point. The letter ‘f’ is called a

“conversion character” and is preceded by a ‘%’ making a “conversion specifier.”’ This tells python that the ‘thing’ to be printed will be a floating point number. The ‘.1’ before the ‘f’ indicates how many decimal places will be displayed. The value printed will be displayed by rounding to the indicated number of places. In this case, only one digit will be printed after the decimal point.

The ‘

%

’ 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’.

'%10s'

%

'Name'

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.

Download