partial string formatting

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

    Not sure if this is ok as a quick workaround, but how about

    s = '{foo} {bar}'
    s.format(foo='FOO', bar='{bar}')
    

    ? :)

    0 讨论(0)
  • 2020-11-28 05:19

    There is one more way to achieve this i.e by using format and % to replace variables. For example:

    >>> s = '{foo} %(bar)s'
    >>> s = s.format(foo='my_foo')
    >>> s
    'my_foo %(bar)s'
    >>> s % {'bar': 'my_bar'}
    'my_foo my_bar'
    
    0 讨论(0)
  • 2020-11-28 05:21

    Thanks to Amber's comment, I came up with this:

    import string
    
    try:
        # Python 3
        from _string import formatter_field_name_split
    except ImportError:
        formatter_field_name_split = str._formatter_field_name_split
    
    
    class PartialFormatter(string.Formatter):
        def get_field(self, field_name, args, kwargs):
            try:
                val = super(PartialFormatter, self).get_field(field_name, args, kwargs)
            except (IndexError, KeyError, AttributeError):
                first, _ = formatter_field_name_split(field_name)
                val = '{' + field_name + '}', first
            return val
    
    0 讨论(0)
提交回复
热议问题