社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何在python中将命名参数动态格式化为字符串?

Roie Labes • 5 年前 • 1488 次点击  

我有一个带参数的数组-对于每个参数,我都有一个名称和一个值。 有没有一种方法可以将其动态格式化为带占位符的字符串?

数组:

[{'name': "a", 'value': "123"}, {'name': "b", 'value': "456"}]

字符串: "blabla {a}"

要求结果: "blabla 123"

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/39031
 
1488 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Martijn Pieters
Reply   •   1 楼
Martijn Pieters    6 年前

因为您的字符串输入已经使用了有效的 string formatting placeholders ,您只需将现有数据结构转换为听写映射名称和值:

template_values = {d['name']: d['value'] for d in list_of_dictionaries}

然后将该字典应用于模板字符串, **mapping 调用语法到 str.format() method 在模板字符串上:

result = template_string.format(**template_values)

演示:

>>> list_of_dictionaries = [{'name': "a", 'value': "123"}, {'name': "b", 'value': "456"}]
>>> template_string = "blabla {a}"
>>> template_values = {d['name']: d['value'] for d in list_of_dictionaries}
>>> template_values
{'a': '123', 'b': '456'}
>>> template_string.format(**template_values)
'blabla 123'