partial string formatting

前端 未结 21 1027
野的像风
野的像风 2020-11-28 04:30

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

F

21条回答
  •  春和景丽
    2020-11-28 05:16

    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.

提交回复
热议问题