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

2024-05-19 12:51:17 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

在不知道每种格式需要多少变量的情况下,如何将字符串列表应用于格式模板列表


2条回答

与硬编码计数不同,只需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

在答复中:

>>> 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 {}']

相关问题 更多 >