Search code examples
pythonstring-formatting

partial string formatting


Is it possible to do partial string formatting with the advanced string formatting methods, similar to the string template safe_substitute() function?

For example:

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

Solution

  • 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))
    

    printing

    FOO {bar}
    

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