我在Python中有一个模板字符串,例如:
'{a} and {b}'
还有两个功能, foo() 和 bar() a 或 b . 我想先检查模板字符串 福() 巴() 所以在最后 福() 和 ,我有完整的插值:
foo()
bar()
a
b
福()
巴()
def foo(template): return template.format(a=10) def bar(template): return template.format(b=20) print(foo(bar('{a} and {b}'))) # 10 and 20 print(bar(foo('{a} and {b}'))) # 10 and 20
有没有一种优雅的方法?
到目前为止,我使用这个作为模板:
'{a} and {{b}}'
foo(bar()) 和 bar(foo()) . 此外,模板变得更难阅读。
foo(bar())
bar(foo())
您可以使用字典保存格式参数,并将其传递给 foo() 和 bar()
format_dictionary = { 'a' : 'cats', 'b' : 'dogs' } print('{a} and {b}'.format(**format_dictionary))
cats and dogs