P3trus P3trus - 1 year ago 66
Python Question

partial string formatting

Is it possible to do partial string formatting with the advanced string formatting methods, similar to the string template


For example:

s = '{foo} {bar}'
s.format(foo='FOO') #Problem: raises KeyError 'bar'

Answer Source

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

import string

class FormatDict(dict):
    def __missing__(self, key):
        return "{" + key + "}"

s = '{foo} {bar}'
formatter = string.Formatter()
mapping = FormatDict(foo='FOO')
print(formatter.vformat(s, (), mapping))


FOO {bar}

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