我有一个参数列表,我想应用于模板格式字符串列表。我的问题是,每个模板字符串都可以接受数量可变的参数。我希望避免硬编码列表,其中列出每个字符串需要多少个参数
counts = [1, 0, 2, 3, 1] # How to get rid of this counts list?
arguments = ["a", "b", "c", "d", "e", "f", "g"]
templates = [
"{} one",
"none",
"{} two {}",
"{} {} three {}",
"one2 {}",
]
start = 0
for i, template in enumerate(templates):
count = counts[i] # a programmatic way to get the count for current template?
print(template.format(*arguments[start : start + count]))
start += count
输出:
a one
none
b two c
d e three f
one2 g
在不知道每种格式需要多少变量的情况下,如何将字符串列表应用于格式模板列表
与硬编码计数不同,只需count每个模板中的有效大括号数。一种简单的方法是:
所以你的程序看起来像这样:
在答复中:
您可以使用在模板或参数中不太可能看到的字符连接所有模板,执行字符串插值,然后分割结果
formatted_templates
现在是:相关问题 更多 >
编程相关推荐