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

编程入门 行业动态 更新时间:2024-10-24 14:16:19
本文介绍了如何在 Python 格式字符串中使用点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想格式化字符串并能够使用点运算符,以便我可以构造包含例如的模板字符串{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 格式字符串中使用点?

本文发布于:2023-10-27 02:56:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1532104.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   格式   如何在   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!