partial string formatting

前端 未结 21 1106
野的像风
野的像风 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:10

    Assuming you won't use the string until it's completely filled out, you could do something like this class:

    class IncrementalFormatting:
        def __init__(self, string):
            self._args = []
            self._kwargs = {}
            self._string = string
    
        def add(self, *args, **kwargs):
            self._args.extend(args)
            self._kwargs.update(kwargs)
    
        def get(self):
            return self._string.format(*self._args, **self._kwargs)
    

    Example:

    template = '#{a}:{}/{}?{c}'
    message = IncrementalFormatting(template)
    message.add('abc')
    message.add('xyz', a=24)
    message.add(c='lmno')
    assert message.get() == '#24:abc/xyz?lmno'
    

提交回复
热议问题