Python string format examples
November 3rd, 2011 Posted in Python, Scientific computing, Software developmentThe 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)
The result is the following string:
'0.1235'
Explanation
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
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'