python - 以键为表达式的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 键不能是变量,因为它考虑了整个字符串。
有没有办法将该键作为变量?
如果不是,我宁愿使用字符串替换。
-巴拉
解决方案
这个怎么样
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()
推荐阅读
- android - ViewPager 内的 EpoxyRecyclerView
- javascript - 如果项目与字符串匹配,请检查 localStorage
- haskell - 如何处理需要额外类型约束的类型类实例
- automated-tests - 如何处理这个元素?
- python - 如何获取orderedDict中具有最小值的对象?
- python - Python 高级模块化算术算法
- plot - 以八度音阶在绘图上获取数据点的值
- javascript - 按 d3 映射中的属性过滤
- asp.net - 如何使用 asp.net core 重写 URL
- python - python:从函数返回异常