Optional formatting

The optional_format() method, the str.format() method and the OptionalFormatter class share the same syntax for format strings.


The optional_format() method is equivalent to OptionalFormatter().format method

Does not require entering all the variables represented by replacement fields in the string. The rest is str.format functionality.


Inherits from BaseFormatter and changes its behavior.


Accessing arguments by position:

>>> from pyformatting import optional_format
>>> optional_format('{0}{2}{1}', 'first')  # only one replacement field will be formatted
>>> optional_format('first{2}{1}', '--', 'third')  # only the second argument will be used
>>> optional_format('{}{}{}', 'first')
>>> optional_format('first{}{}', '--', 'third')  # empty replacement fields will use all arguments

Accessing arguments by name:

>>> optional_format('{a}{b}{c}', a='first')
>>> optional_format('first{b}{c}', a='--', c='third')