如何格式化可变数量的参数?

How to format variable number of arguments?

我有一个要应用于模板格式字符串列表的参数列表。我的问题是每个模板字符串都可以采用可变数量的参数。我想避免使用硬编码列表列出每个字符串需要多少个参数

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 每个模板中有效大括号的数量。一个简单的方法是这样的:

>>> "{} {} three {}".count("{}")
3
>>> "none".count("{}")
0

所以你的程序看起来像这样:

arguments = ["a", "b", "c", "d", "e", "f", "g"] 
templates = [
    "{{}} one",
    "none",
    "{} two {}",
    "{} {} three {}",
    "one2 {}",
    "and {{literal}} braces {{}}"
]

start = 0
for template in templates:
    count = template.count("{}")
    print(template.format(*arguments[start : start + count]))
    start += count

在 REPL 中:

>>> arguments = ["a", "b", "c", "d", "e", "f", "g"]
>>> templates = [
...     "{} one",
...     "none",
...     "{} two {}",
...     "{} {} three {}",
...     "one2 {}",
...     "and {{literal}} braces {{}}"
... ]
>>>
>>> start = 0
>>> for template in templates:
...     count = template.count("{}")
...     print(template.format(*arguments[start : start + count]))
...     start += count
...
{} one
none
b two c
d e three f
one2 g
and {literal} braces {}

您可以使用不太可能在模板或参数中看到的字符连接所有模板,进行字符串插值,然后拆分结果。

templates = [
    "{} one",
    "none",
    "{} two {}",
    "{} {} three {}",
    "one2 {}",
    "and {{literal}} braces {{}}"
]
arguments = ["a", "b", "c", "d", "e", "f", "g"] 

joined_template = chr(1).join(templates)

formatted_string = joined_template.format(*arguments)

formatted_templates = formatted_string.split(chr(1))

formatted_templates 现在是:

['a one',
 'none',
 'b two c',
 'd e three f',
 'one2 g',
 'and {literal} braces {}']