Click here to view code image
>>> test1 = 10
>>> test2 = 3
>>> result = test1 / test2
>>> print(result)
3.3333333333333335
>>> print('The result is {0:.2f}'.format(result))
The result is 3.33
>>>
Without the format() function, the print() function displays the result variable value with
the repeating decimal places. The .2f format tells Python to round the value to two decimal places,
using a fixed-point format.
Sign Formatting
The format() function provides a way for you to define how Python handles the sign in a number.
The plus sign (+) tells Python that a sign should be used for both positive and negative numbers in the
output. The negative sign (-) tells Python that a sign should be used only for negative numbers. The
default is to use the sign only for negative numbers.
Here are a few examples of using the sign-formatting codes:
Click here to view code image
>>> test1 = 45
>>> print(test1)
45
>>> print('{0:+}'.format(test1))
+45
>>> test2 = -12.56
>>> print(test2)
-12.56
>>> print('{0:+.2f}'.format(test2))
-12.56
>>>
If you need your numeric columns to line up in the output, you can use a space for the sign formatting.
The space indicates that a leading space should be used on positive numbers, and a minus sign should
be used on negative numbers.
Positional Formatting
If you have to work with lining up numbers in columns, there are a few other formatting codes you can
use to help out. Table 10.6 describes the tools that are available to help align the numbers in your
output.
TABLE 10.6 Positional-Formatting Codes
With the left-align, right-align, and center formats, you specify the number of spaces reserved for the