Python supports format from 2.6, a new, easier-to-read string formatting method.
1. Replace the old% output
Old formatted output method:
# !/usr/bin/python ' Tom ' =print'%s is%d yearsold' % (name,age)
Format the output with the Format function:
# !/usr/bin/python ' Tom ' =print'{0} is {1} years'. Format (name,age)
Compared to the old output mode, the string's format function can accept an unlimited number of parameters, the position can be out of order, can not be used or multiple times.
2. Can be used to limit the number of decimal places
For example
# !/usr/bin/python # Keep 3 digits after the decimal point, 0.333 Print ' {0:.3f} '. Format (1.0/3)
3. Fill in alignment
# !/usr/bin/python # output ' __hello___ ', length is 10, the length is insufficient when ' _ ' to complement
#其中 ' ^ ' indicates center alignment, ' < ' left-aligned, ' > ' right-aligned
Print ' {0:_^10} '. Format ('hello')
Python string Format function