代码之家  ›  专栏  ›  技术社区  ›  norok2

在多个步骤中应用“str.format()”(或str.format_map()`)【重复】

  •  0
  • norok2  · 技术社区  · 5 年前

    我在Python中有一个模板字符串,例如:

    '{a} and {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()) . 此外,模板变得更难阅读。

    1 回复  |  直到 5 年前
        1
  •  0
  •   user10417531 user10417531    5 年前

    您可以使用字典保存格式参数,并将其传递给 foo() bar()

    format_dictionary = {
        'a' : 'cats',
        'b' : 'dogs'
    }
    print('{a} and {b}'.format(**format_dictionary))
    
    cats and dogs