繁体   English   中英

如何格式化 arguments 的变量号?

[英]How to format variable number of arguments?

我有一个 arguments 列表我想应用于模板格式字符串列表。 我的问题是每个模板字符串可以采用可变数量的 arguments。 我想避免硬编码每个字符串需要多少 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

Output:

一个
没有任何
b 两个 c
德三f
一个2克

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

无需对计数进行硬编码,只需计算每个模板中有效大括号的数量即可。 一个简单的方法是这样的:

>>> "{} {} 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 {}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM