python: dots in the name of variable in a format string

后端 未结 3 1161
北荒
北荒 2021-01-11 16:41

Say I\'ve got a dictionary with dots in the name of fields, like {\'person.name\': \'Joe\'}. If I wanted to use this in str.format, is it possible

3条回答
  •  温柔的废话
    2021-01-11 17:13

    I had similar issue and I solved it by inheriting from string.Formatter:

    import string
    
    class MyFormatter(string.Formatter):
        def get_field(self, field_name, args, kwargs):
            return (self.get_value(field_name, args, kwargs), field_name)
    

    however you can't use str.format() because it's still pointing to old formatter and you need to go like this

    >>> MyFormatter().vformat("{a.b}", [], {'a.b': 'Success!'})
    'Success!'
    

提交回复
热议问题