简体   繁体   中英

How to format variable number of arguments?

I have a list of arguments I would like to apply to a list of template format strings. My issue is that each template string can take a variable number of arguments. I want to avoid having a hardcoded list of how many arguments each string takes

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:

a one
none
b two c
de three f
one2 g

How can I apply a list of strings to a list of format templates without knowing how many variables each format requires?

Rather than hard coding your count, just count the number of valid braces in each template. A simplistic way of doing this is like this:

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

So your program would look something like this:

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

In the 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 {}

You could join all your templates using a character that you're unlikely to see in the templates or arguments, do the string interpolation, and then split the result.

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 is now:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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