如何在 Python 格式字符串中使用点? [英] How to use a dot in Python format strings?
问题描述
我想格式化字符串并能够使用点运算符,以便我可以构造包含例如的模板字符串{user.name}
, {product.price}
.
I want to format a string and be able to use the dot operator, so that I can construct template strings containing e.g. {user.name}
, {product.price}
.
我试过了:
'Hello {user.name}'.format( {'user': { 'name': 'Markus' } } )
KeyError: 'user'
'Hello {user.name}'.format( **{'user': { 'name': 'Markus' } } )
AttributeError: 'dict' object has no attribute 'name'
有办法吗?
推荐答案
Python dict
对象在默认情况下无法访问属性(即使用点表示法).因此,您可以选择使用更丑陋的括号表示法:
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' } } )
或者您可以将数据包装在一个点可访问的对象中.您可以从 PyPI 安装一些可访问属性的字典类,例如 stuf.
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' } }) )
我倾向于将我的集合保存在 stuf
对象中,以便我可以通过属性轻松访问它们.
I tend to keep my collections in stuf
objects so that I can easily access them by attribute.
这篇关于如何在 Python 格式字符串中使用点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!