以键作为表达式的python字符串模板
我正在使用字符串模板替换占位符。我当前的场景是将变量作为键,而不是要替换的字符串 下面是我试图实现的一个例子以键作为表达式的python字符串模板,python,string,stringtemplate,Python,String,Stringtemplate,我正在使用字符串模板替换占位符。我当前的场景是将变量作为键,而不是要替换的字符串 下面是我试图实现的一个例子 import traceback from string import Template def test_substitute(): try: tpl = Template("My $testname is ...") name = 'testname' tpl_str = tpl.substitute(na
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()
在上面的示例中,名称是一个变量,它保存任何字符串,如“TestNoNT”或“TestNAME1”,但i键不能是一个变量,因为它考虑了整个字符串。 有没有办法将该键作为变量
如果不是,我宁愿用字符串替换 -巴拉这个怎么样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()
我不完全清楚你想完成什么。在创建模板字符串时,是否尝试从变量设置键值?在这种情况下,
tpl=Template(f“My{testname}是…”)
(当然,如果是python 3.8或更高版本)