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 add more as I have time:
Formatting Numbers in Python Strings
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)
Result:
'1.2346e-01'
Format decimal fraction as percentage
Pass in a decimal fraction; the fraction will be multiplied by 100 and the percent sign will be added for you:
"{:.1%} of programmers prefer Python".format(0.473726)
Result (note correct rounding behavior):
47.4% of programmers prefer Python
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.
Date Formatting
You have two options to print formatted dates. There is a type-specific date formatter, which is mentioned in the string documentation, but not otherwise well-documented. An exact equivalent is to use basic string formatting, but format the datetime object as a string using the strftime method.
import datetime d = datetime.datetime(2010, 7, 4, 12, 15, 58) '{:%Y-%m-%d %H:%M:%S}'.format(d) '{}'.format(d.strftime('%Y-%m-%d %H:%M:%S'))
Either method creates an identical string:
'2010-07-04 12:15:58'
Text String Formatting
Tabular text output
Sometimes you need to write out multiple lines in a table-like format. The easiest way to do that is by defining a format string with fixed widths for each column. If you define the format string outside of your print statements, you don’t have to worry about updating multiple format strings every time you tweak the column widths.
listFormatString = '{:32} {:24} {:24}' print(listFormatString.format('Name', 'Created', 'Updated')) for item in items: print(listFormatString.format(item['name'], item['createdTime'], item['modifiedTime']))
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 3.x, 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'
References
Thank you very much for this examples. I’ve solved my writting problem 😉
Thank you very much for explaining it in easy and useful way.