[英]python string template with key as expression
I am using string template to replace placeholders.我正在使用字符串模板来替换占位符。 My current scenario is to have variable for the key instead of the string to be replaced.我当前的方案是为键使用变量而不是要替换的字符串。
Below is an example of what i am trying to achieve.下面是我试图实现的一个例子。
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()
In the above example, name is a variable that holds any string like 'testname' or 'testname1' but i the key cannot be a variable as it consider a whole string.在上面的例子中,name 是一个变量,它包含任何像 'testname' 或 'testname1' 这样的字符串,但我的键不能是一个变量,因为它考虑了一个完整的字符串。
Is there a way to make that key as a variable?有没有办法将该键作为变量?
If not i would rather go with string replace.如果不是,我宁愿使用字符串替换。
-Bala -巴拉
How about this这个怎么样
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.