30
1 The First Few Steps
In the first call to print,
print(’real={:.3f}, integer={:d}, string={:s}’.format(r, i, s))
:.3f tells Python that the floating point number r is to be written as compactly as
possible in decimal notation with three decimals, :d tells Python that the integer i
is to be written as compactly as possible, and :s tells Python to write the string s.
In the second call to print,
print(’real={:9.3e}, integer={:5d}, string={:s}’.format(r, i, s))
the interpretation is the same, except that r and i now should be formatted according
to :9.3e and :5d, respectively. For r, this means that its float value will be written
in scientific notation (the e) with 3 decimals, in a field that has a width of 9
characters. As for i, its integer value will be written in a field of width 5 characters.
Other ways of formatting the numbers would also have been possible. 20 For
example, specifying the printing of r rather as :9.3f (i.e., f instead of e), would
give decimal notation, while with :g, Python itself would choose between scientific
and decimal notation, automatically choosing the one resulting in the most compact
output. Typically, scientific notation is appropriate for very small and very large
numbers and decimal notation for the intermediate range.
Printing with old string formatting
There is another older string formatting that, when used with print, gives the
same printout as the string format method. Since you will meet it frequently
in Python programs found elsewhere, you better know about it. With this
formatting, the calls to print in the previous example would rather read
print(’real=%.3f, integer=%d, string=%s’ % (r, i, s))
print(’real=%9.3e, integer=%5d, string=%s’ % (r, i, s))
As you might guess, the overall “structure” of the argument to print is the
same as with the string format method, but, essentially, % is used instead of {}
(with : inside) and .format.
An Example: Printing Nicely Aligned Columns A typical example of when
formatted printing is required, arises when nicely aligned columns of numbers are to
be printed. Suppose we want to print a column of t values together with associated
function values g(t) = t sin(t) in a second column.
We could achieve this in the following way (note that, repeating the same
set of statements multiple times, like we do in the following code, is not good
programming practice—one should use a loop. You will learn about loops in
Chap. 3.)
from math import sin
t0 = 2
20 https://docs.python.org/3/library/string.html#format-string-syntax.
Précédent

- 52/350

Suivant