区别:
<font style="color:rgb(199, 37, 78);background-color:rgb(249, 242, 244);">substitute(mapping={}, /, **kwds)</font>
:执行模板替换并返回一个新字符串。映射是任何类似于字典的对象,其键与模板中的占位符匹配。<font style="color:rgb(199, 37, 78);background-color:rgb(249, 242, 244);">safe_substitute(mapping={}, /, **kwds)</font>
:与substitute()相似。不同之处在于,如果映射和kwds中缺少占位符,而不是引发KeyError异常,则原始占位符将完整显示在结果字符串中。
1. 替换字符串中占位符
from string import Template
def test_example(dics):
template = "$who like $what"
template_new = Template(template).substitute(dics)
return f'模板:{template}\n替换后:{template_new}'
dics = {'who':"he","what":"running"}
print(test_example(dics))
输出结果:
模板:$who like $what
替换后:he like running
2.替换yaml文件中的占位符
yaml文件
name: Tom Smith
age: $age
from string import Template
def test_example(dics):
with open(r'./testData/test.yml',encoding='utf-8') as f:
yaml_str = f.read()
print(type(yaml_str),yaml_str)
str1 = Template(yaml_str).substitute(dics)
print(str1)
student = yaml.full_load(str1)
print(type(student),student)
dics = {"age":20}
print(test_example(dics))
输出结果:
<class 'str'>
替换完后字符串:
name: Tom Smith
age: 20
<class 'dict'>
加载yml字典内容:
{'name': 'Tom Smith', 'age': 20}