区别:

  1. <font style="color:rgb(199, 37, 78);background-color:rgb(249, 242, 244);">substitute(mapping={}, /, **kwds)</font>执行模板替换并返回一个新字符串。映射是任何类似于字典的对象,其键与模板中的占位符匹配。
  2. <font style="color:rgb(199, 37, 78);background-color:rgb(249, 242, 244);">safe_substitute(mapping={}, /, **kwds)</font>与substitute()相似。不同之处在于,如果映射和kwds中缺少占位符,而不是引发KeyError异常,则原始占位符将完整显示在结果字符串中。

1. 替换字符串中占位符

  1. from string import Template
  2. def test_example(dics):
  3. template = "$who like $what"
  4. template_new = Template(template).substitute(dics)
  5. return f'模板:{template}\n替换后:{template_new}'
  6. dics = {'who':"he","what":"running"}
  7. print(test_example(dics))
  8. 输出结果:
  9. 模板:$who like $what
  10. 替换后:he like running

2.替换yaml文件中的占位符

  1. yaml文件
  2. name: Tom Smith
  3. age: $age
  1. from string import Template
  2. def test_example(dics):
  3. with open(r'./testData/test.yml',encoding='utf-8') as f:
  4. yaml_str = f.read()
  5. print(type(yaml_str),yaml_str)
  6. str1 = Template(yaml_str).substitute(dics)
  7. print(str1)
  8. student = yaml.full_load(str1)
  9. print(type(student),student)
  10. dics = {"age":20}
  11. print(test_example(dics))
  12. 输出结果:
  13. <class 'str'>
  14. 替换完后字符串:
  15. name: Tom Smith
  16. age: 20
  17. <class 'dict'>
  18. 加载yml字典内容:
  19. {'name': 'Tom Smith', 'age': 20}