johnstowers.co.nz ~ / blog / python print / string format reference

Python Print / String Format Reference

Python has two major ways for creating formatted strings.

string.format()

NumberFormatOutputDescription
3.1415926{:.2f}3.142 decimal places
3.1415926{:+.2f}+3.142 decimal places with sign
-1{:+.2f}-1.002 decimal places with sign
2.71828{:.0f}3No decimal places
5.432{:0>2.0f}05No decimal places, left pad with zeros, width 2
5{:0>2d}05Pad number with zeros (left padding, width 2)
5{:x<4d}5xxxPad number with x’s (right padding, width 4)
10{:x<4d}10xxPad number with x’s (right padding, width 4)
1000000{:,}1,000,000Number format with comma separator
0.25{:.2%}25.00%Format percentage
1000000000{:.2e}1.00e+09Exponent notation
13{:10d}13Right aligned (default, width 10)
13{:<10d}13Left aligned (width 10)
13{:^10d}13Center aligned (width 10)