Skip to content Skip to sidebar Skip to footer

Python: Dots In The Name Of Variable In A Format String

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? My first instinct was 'Name: {perso

Solution 1:

'Name: {0[person.name]}'.format({'person.name': 'Joe'})

Solution 2:

One way to work around this is to use the old % formatting (which has not been deprecated yet):

>>>print'Name: %(person.name)s' % {'person.name': 'Joe'}
Name: Joe

Solution 3:

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

import string

classMyFormatter(string.Formatter):
    defget_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!'

Post a Comment for "Python: Dots In The Name Of Variable In A Format String"