python-Template(模板字符串)
一、导入
这个类位于string模块下
from string import Template
二、要先实例化对象,实例化的时候要传入字符串
1、
template = Template("今晚打老虎, 我喜欢头发长,身材好,屁股白,腿细,胸大的年轻漂亮女孩!")
2、Template以$为特殊标识符,它具有以下规则:
- 它的主要实现方式为$xxx,其中xxx是满足python命名规则的字符串,即不能以数字,不能为关键字
- 如果 x x x 需要和其他字符串接触时,可以 将 x x x 包裹起来,例如 xxx需要和其他字符串接触时,可以{}将xxx包裹起来, 例如 xxx需要和其他字符串接触时,可以将xxx包裹起来,例如{aaa}aaa
3、Template中有两个重要的方法:substitute和safe_substitute
这两个方法都可以通过获取参数返回字符串
template = Template("There $a and $b")
result = template.substitute(a="apple", b="orange")
print(result) # substitute
还可以通过字典直接传递数据:
template = Template("There $a and $b")
result = template.substitute({"a": "apple", "b": "orange"})
print(result) # safe_substitute
区别在于参数缺少时的处理方式:
substitute:如果少穿参数或者参数传递的错误会直接报错
template = Template("There $a and $b")
result = template.substitute(a="apple")
print(result) # KeyError: 'b'
safe_substitute:如果少传参数或者传递的参数错误,并不会报错,并且会将原始占位符将完整显示在结果字符串中。
template = Template("There $a and $b")
result = template.safe_substitute({"a": "apple"})
print(result) # There apple and $b