Py学习  »  Python

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

Roie Labes • 4 年前 • 681 次点击  

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

数组:

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

字符串: "blabla {a}"

要求结果: "blabla 123"

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

因为您的字符串输入已经使用了有效的 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'