以键为表达式的python字符串模板

问题描述

我正在使用字符串模板替换占位符。我目前的情况是为键设置变量,而不是要替换的字符串。

下面是我要实现的目标的一个示例。

import traceback
from string import Template

def test_substitute():
    try:
        tpl = Template("My $testname is ...")
        name = 'testname'
        tpl_str = tpl.substitute(name='test')
        print(tpl_str)
    except:
        traceback.print_exc()

if __name__=="__main__":
    test_substitute()

在上面的示例中,name是一个变量,其中包含“ testname”或“ testname1”之类的任何字符串,但我的键不能是变量,因为它考虑了整个字符串。

有没有办法将该键作为变量?

如果不是,我宁愿使用字符串替换。

-巴拉

解决方法

怎么样

import traceback
from string import Template

def test_substitute():
    try:
        tpl = Template("My $testname is ...")
        name = 'testname'
        tpl_str = tpl.substitute(**{name: 'test'})
        print(tpl_str)
    except:
        traceback.print_exc()

if __name__=="__main__":
    test_substitute()