Search code examples
pythonpython-3.xformat-string

Example of using [0][width] in format specifier


I have the following format string:

>>> '{num:+,.4f}'.format(num=-200000)

This uses the:

  • [sign]
  • [grouping_option]
  • [.precision]
  • [type]

Options in the format specifier defined here.

The format spec is defined as:

format_spec     ::=  [[fill]align][sign][#] here ==> [0][width]<== here [grouping_option][.precision][type]

What would be an example of the [0] and [width] options? What are those used for?


Solution

  • The Width means pad the entire number on the left so that it produces at least that many characters, useful when the numbers need to line up. The 0 means pad the width with zeros instead of spaces.

    >>> '{num:+20,.4f}'.format(num=-200000)
    '       -200,000.0000'
    >>> '{num:+020,.4f}'.format(num=-200000)
    '-00,000,200,000.0000'