0%

Python string format

  • ^, <, > are centered, left-aligned, right-aligned, followed by width, with a padded character after the:, which can only be one character. If not specified, the default is filled with spaces.
  • + means to display + sign before the positive number and the - sign before the negative number.
  • space means to add a space before the positive number.
  • b, d, o, and x are binary, decimal, octal, and hexadecimal, respectively.
1
2
>>> print("{:.2f}".format(3.1415926));
3.14
Number Format Output Description
3.1415926 {:.2f} 3.14 Keep two decimal places
3.1415926 {:+.2f} +3.14 Keep two decimal places with symbol
-1 {:+.2f} -1.00 Keep two decimal places with symbol
2.71828 {:.0f} 3 Without decimals
5 {:0>2d} 05 Fill with 0 (fill left, width 2)
5 {:x<4d} 5xxx Fill with 0 (fill right, width 4)
10 {:x<4d} 10xx Fill with 0 (fill right, width 4)
1000000 {:,} 1,000,000 Comma separated number format
0.25 {:.2%} 25.00% Percentage format
1000000000 {:.2e} 1.00e+09 Index notation
13 {:>10d} 13 Align right (default, width is 10)
13 {:<10d} 13 Align left (width is 10)
13 {:^10d} 13 Align in the middle (width is 10)
11 ‘{:b}’.format(11) 1011 Binary
11 ‘{:d}’.format(11) 11 Decimal
11 ‘{:o}’.format(11) 13 Octal
11 ‘{:x}’.format(11) b Hexadecimal
11 ‘{:#x}’.format(11) 0xb Hexadecimal with lowercase 0x
11 ‘{:#X}’.format(11) 0XB Hexadecimal with uppercase 0X