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 render the corresponding 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
| Symbol | Meaning |
|---|---|
< |
Left-align within the given width |
> |
Right-align within the given width |
^ |
Center-align within the given width |
= |
Force padding between sign and digits (numbers only) |
>>> '{:<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
| Type | Applies to | Effect |
|---|---|---|
f |
float | Fixed-point notation |
e |
float | Scientific notation (lowercase) |
E |
float | Scientific notation (uppercase) |
g |
float | General (shortest of f or e) |
% |
float | Percentage |
b |
int | Binary |
| `` | int | Fixed-point decimal |
c |
int | Unicode chaarcter |
d |
int | Decimal |
o |
int | Octal |
x |
int | Hexadecimal (lowercase) |
X |
int | Hexadecimal (uppercase) |
s |
str | String (default) |
>>> '{:.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 displyaed.
>>> '{:.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