Comprehensive Guide to Python's Format Specification Mini-Language
When you call str.format(), each replacement field may contain a format specifier that tells Python exactly how to rander the corrresponding argument. The specifier is introduced by a colon : and is composed of the following optional components in order:
{[name][!conversion][:[[fill]align][sign][#][0][width][grouping][.precision][type]]}
Alignment & Width
>>> '{:<10}'.format('left')
'left '
>>> '{:>10}'.format('right')
' right'
>>> '{:^10}'.format('center')
' center '
Think of < and > as arrows pointing to the side where the content should stick.
Fill Character
Any character placed before the alignment symbol becomes the padding character.
>>> '{:*^12}'.format('Python')
'***Python***'
Numeric Options
+: always show sign-: show sign only for negatives (default)space: leading space for positives#: alternate form (prefix0b,0o,0x)0: zero-padding (same asfill='0' align='=')
>>> '{:+05d}'.format(42)
'+0042'
>>> '{:#x}'.format(255)
'0xff'
Precision & Types
>>> '{:.2f}'.format(3.1415926)
'3.14'
>>> '{:.2e}'.format(123456789)
'1.23e+08'
>>> '{:,.0f}'.format(1e6)
'1,000,000'
String Truncation
For strings, .precision limits the number of characters displayed.
>>> '{:.5}'.format('全国二级计算机考试')
'全国二级计'
Multiple Representations of One Value
>>> n = 276
>>> '{0:b} {0:c} {0:d} {0:o} {0:x} {0:X}'.format(n)
'100010100 Ť 276 424 114 72'
Putting It All Together
>>> '{:0>+8.2f}'.format(-3.141)
'-0003.14'
The specifier above means:
0– use0as fill character>– right-align+– always show sign8– total width 8 characters.2f– fixed-point with 2 digits after decimal