The format method for Python strings (introduced in 2.6) is very flexible and powerful. It’s also easy to use, but the documentation is not very clear. It all makes sense with a few examples. I’ll start with one and add more as I have time:
Formatting a floating-point number
"{0:.4f}".format(0.1234567890) "{0:.4f}".format(10.1234567890)
The result is the following string:
'0.1235' '10.1235'
Braces { } are used to enclose the “replacement field”
0 indicates the first argument to method format
: indicates the start of the format specifier
.4 indicates four decimal places
f indicates a floating-point number
Align floating-point numbers at the decimal point
There is no format specifier that aligns numbers at the decimal point. Decimal-point alignment is accomplished by fixing the field width, which is set by placing a number before the decimal point in the format string. Compare the previous example to the output shown below:
"{0:8.4f}".format(0.1234567890) "{0:8.4f}".format(10.987654321)
Result:
' 0.9877' ' 10.9877'
Scientific Notation
"{0:.4e}".format(0.1234567890)
Output:
'1.2346e-01'
Multiple Arguments
In Python 2.6 you can include multiple arguments like this:
"sin({0:.4f}) = {1:.4e}".format(0.1234567890, sin(0.123456789))
'sin(0.1235) = 1.2314e-01'
In Python 2.7 and later, you may omit the first integer from each replacement field, and the arguments to format will be taken in order:
"sin({:.4f}) = {:.4e}".format(0.1234567890, sin(0.123456789))
'sin(0.1235) = 1.2314e-01'
Leave space for a minus sign
"{: .4e}".format(0.098765) "{: .4e}".format(-0.1234567)
Output:
9.8765e-02 -1.2346e-01
Note that there is a space between the colon and the dot in the format specifier. The decimal points for the two numbers are aligned in the output, which is handy for printing tabular data.
Thank you very much for this examples. I’ve solved my writting problem 😉
LikeLike
Thank you very much for explaining it in easy and useful way.
LikeLike