简体   繁体   English

如何在Python格式字符串中使用点?

[英]How to use a dot in Python format strings?

I want to format a string and be able to use the dot operator, so that I can construct template strings containing eg {user.name} , {product.price} . 我想格式化一个字符串并能够使用点运算符,这样我就可以构造包含例如{user.name}{product.price}模板字符串。

I tried this: 我试过这个:

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

'Hello {user.name}'.format( **{'user': { 'name': 'Markus' } } )
AttributeError: 'dict' object has no attribute 'name'

Is there a way to do it? 有办法吗?

Python dict objects are unfortunately not attribute accessible (ie with the dot notation) by default. 遗憾的是,Python dict对象默认情况下不是属性可访问的(即使用点表示法)。 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 . 您可以从PyPI安装一些属性可访问的字典类,例如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. 我倾向于将我的集合保存在stuf对象中,以便我可以通过属性轻松访问它们。

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, eg a custom class or collections.namedtuple : 或者,将实际具有该属性的对象放在字典中,例如自定义类或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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM