【发布时间】:2021-06-04 21:29:30
【问题描述】:
我有一个参数列表,我想将其应用于模板格式字符串列表。我的问题是每个模板字符串都可以采用可变数量的参数。我想避免每个字符串需要多少个参数的硬编码列表
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
输出:
一个
无
b 两个 c
d e 三f
一个2克
如何在不知道每种格式需要多少变量的情况下将字符串列表应用于格式模板列表?
【问题讨论】:
-
您也可以考虑对字符串进行正则表达式,这可能是 Python 在后台所做的。