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

*爱你&永不变心* 提交于 2019-11-30 23:47:55

问题


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: {person.name}'.format(**{'person.name': 'Joe'})

but this would only work if my dict were shaped like

{'person':{'name':Joe}}

The relevant manual docs section doesn't mention anyway of escaping the dot.

(Sidenote: I thought that generally

def func(**kw): print(kw)
func(**{'a.b': 'Joe'})

would cause an error, but the **-expanded function call seems to work even if they're not valid identifiers! It does error out on non-strings though. o_O)


回答1:


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



回答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



回答3:


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!'


来源:https://stackoverflow.com/questions/7934620/python-dots-in-the-name-of-variable-in-a-format-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!