通过连接其值来格式化列表

时间:2018-05-25 10:29:34

标签: python

说我有一本字典:

data = {
"user" : {
   "properties" : ["i1", "i2"]
}
}

以下字符串:

txt = "The user has properties {user[properties]}"

我希望:

txt.format(**data)

等于:

The user has properties i1, i2

我相信要实现这一点,我可以继承str.format使用的格式化程序,但遗憾的是我不确定如何继续。我很少将标准Python类子类化。请注意,写{user[properties][0]}, {user[properties][1]}对我来说不是一个理想的选择。我不知道列表中有多少项,因此我需要使用正则表达式来识别匹配项,然后在data中找到相关值并将匹配的文本替换为{user[properties][0]}, {user[properties][1]}str.format负责处理字符串值的所有索引,因此非常实用。

2 个答案:

答案 0 :(得分:1)

只需加入data["user"]["properties"]

中的项目即可
txt = "The user has properties {properties}"
txt.format(properties = ", ".join(data["user"]["properties"]))

这里有live example

答案 1 :(得分:0)

我最终使用jinja2软件包来满足我所有的格式化需求。它非常强大,我真的推荐它!