How to use a dot in Python format strings?

為{幸葍}努か 提交于 2019-12-01 03:31:15

Python dict objects are unfortunately not attribute accessible (i.e. with the dot notation) by default. So you can either resign yourself to the uglier brackets notation:

'Hello {user[name]}'.format( **{'user': { 'name': 'Markus' } } )

Or you can wrap your data in a dot-accessible object. There are a handful of attribute-accessible dictionary classes you can install from PyPI, such as stuf.

from stuf import stuf

'Hello {user.name}'.format( **stuf({'user': { 'name': 'Markus' } }) )

I tend to keep my collections in stuf objects so that I can easily access them by attribute.

The minimal change is to use square brackets in your template, rather than a period:

              # v Note
>>> 'Hello {user[name]}'.format(**{'user': {'name': 'Markus'}})
'Hello Markus'

Alternatively, put objects that actually have that attribute in the dictionary, e.g. a custom class or collections.namedtuple:

>>> class User(object):
    def __init__(self, name):
        self.name = name


>>> 'Hello {user.name}'.format(**{'user': User('Markus')})
'Hello Markus'

Note also that if you're writing out the literal you can just use a keyword argument:

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