【问题标题】:How to format named params into strings dynamically in Python?如何在 Python 中动态地将命名参数格式化为字符串?
【发布时间】:2018-10-08 08:06:33
【问题描述】:

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

数组:

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

字符串:"blabla {a}"

必填结果:"blabla 123"

【问题讨论】:

  • 您的数据采用这种格式是否有原因?您应该只将名称/值对存储在字典中,而不是字典列表。
  • 注意:Python 使用名称list,而不是array,用于可变序列数据结构。 separate array module 仅支持每个值的单一数字类型。

标签: python string format


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2013-07-27
    • 2011-01-27
    • 1970-01-01
    • 1970-01-01
    • 2010-10-09
    • 2012-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多