首页 > 解决方案 > 以键为表达式的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' 但 i 键不能是变量,因为它考虑了整个字符串。

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

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

-巴拉

标签: pythonstringstringtemplate

解决方案


这个怎么样

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()

推荐阅读