partial string formatting partial string formatting python python

partial string formatting


If you know in what order you're formatting things:

s = '{foo} {{bar}}'

Use it like this:

ss = s.format(foo='FOO') print ss >>> 'FOO {bar}'print ss.format(bar='BAR')>>> 'FOO BAR'

You can't specify foo and bar at the same time - you have to do it sequentially.


You could use the partial function from functools which is short, most readable and also describes the coder's intention:

from functools import partials = partial("{foo} {bar}".format, foo="FOO")print s(bar="BAR")# FOO BAR


You can trick it into partial formatting by overwriting the mapping:

import stringclass FormatDict(dict):    def __missing__(self, key):        return "{" + key + "}"s = '{foo} {bar}'formatter = string.Formatter()mapping = FormatDict(foo='FOO')print(formatter.vformat(s, (), mapping))

printing

FOO {bar}

Of course this basic implementation only works correctly for basic cases.