Sunday, July 27, 2014

Numeric formatting with Python - Example Table

Sometimes it's hard to remember all the properties, specially if we are not using them often. Here is a summary table that aims to show some examples on the format property that Python gives us to format numbers using the format string method.

NumberFormatOutputDescription
3.1415926{:.2f}3.142 decimal places
3.1415926{:+.2f}3.142 decimal places with sign
-1{:+.2f}-12 decimal places with sign
2.71828{:.0f}3No decimal places
5{:0>2d}5Pad 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)

No comments:

Post a Comment