Template类创建模板替换字符串
Template类创建模板替换字符串
1.概述
如果你在操作字符串,如果你操作的字符串内容很多,希望字符串中的内容能够根据规则动态替换,并且在长篇幅的字符串中需要替换任意位置任意次数的字符,使用str提供的replace方法代码会写的非常复杂,且出错不易排查。
在这个场景中试试Template类把,他能够创建一个模板替换字符串。
2.Template类介绍
Python中Template是string中的一个类,可以创建一个模板将字符串的格式固定下来,重复利用。使用它来解决需要在一个字符串中替换多处内容将会减轻开发代码的复杂度,使用起来非常简单。
2.1.Template类替换字符串基本操作
1.替换字符串内容
- Template构造器接收一个待替换的字符串,字符串中${}里面的字符为需要替换的内容。创建一个模板就完成了。
- substitute方法参数接收替换的内容,替换模板中的字符串。
from string import Template
s1 = "我在用 ${code} ${num} 开发项目"
s = Template(s1)
print(s.substitute(code='Python',num=3))
运行上面的代码,下面输出了替换后的字符串。
我在用 Python 3 开发项目
2.safe_substitute方法替换substitute方法
safe_substitute和substitute方法在用法上都是一样的,但是safe_substitute是安全的可以避免在写代码时候一些疏忽报错。
在开发中建议使用safe_substitute方法,下面通过几个例子介绍下他们的区别。
${}里面的内容和括号有空格会报错
from string import Template
# ${ code }: 括号和code之间有空格
s1 = "我在用 ${ code } ${num} 开发项目"
s = Template(s1)
print(s.safe_substitute(code='Python',num=3))
from string import Template
# ${ code }: 括号和code之间有空格
s1 = "我在用 ${ code } ${num} 开发项目"
s = Template(s1)
print(s.safe_substitute(code='Python',num=3))
print(s.substitute(code='Python',num=3))
运行上面的代码,从结果中可以看出safe_substitute原样输出了变量,没有报错。substitute方法则报错
# safe_substitute输出结果
我在用 ${ code } 3 开发项目
# substitute输出结果
raise ValueError('Invalid placeholder in string: line %d, col %d' %
替换的变量和模板中待替换变量数量不一致则会报错。
from string import Template
# ${ code }: 括号和code之间有空格
s1 = "我在用 ${code} ${num} 开发项目"
s = Template(s1)
# 没有替换num
print(s.safe_substitute(code='Python'))
from string import Template
# ${ code }: 括号和code之间有空格
s1 = "我在用 ${code} ${num} 开发项目"
s = Template(s1)
print(s.substitute(code='Python'))
运行上面的代码,从结果中可以看出safe_substitute原样输出了变量,没有报错。substitute方法则报错
# safe_substitute输出结果
我在用 Python ${num} 开发项目
# substitute输出结果
KeyError: 'num'
2.2.自定义替换字符串符号
如果你不想使用Template类提供的默认$
符号作为替换字符的特殊符号,可以自定义一个喜欢的符号,例如下面使用了&
符号替换$
符号实现替换字符串。
首先创建一个类,继承Template类,重写类的delimiter属性即可修改默认的$
符号
from string import Template
# 继承Template类
class MyTemplate(Template):
# 重写delimiter类属性,它的作用是识别字符串模板中待替换的字符的特殊符号
delimiter = '&'
def replace():
s1 = "我在用 &{code} &{num} 开发项目"
t = MyTemplate(s1)
rp = t.safe_substitute(code='Python',num=3)
print(f'使用自定义的替换字符串符号,替换字符串结果:{rp}')
replace()
运行上面的代码,下面显示&
符号替换了字符串
使用自定义的替换字符串符号,替换字符串结果:我在用 Python 3 开发项目
2.3.Template运用到项目中
现在开发一个接口测试功能,前端传来的headers中Content-Type属性值是一个待替换的变量。需要将它替换成实际值后在发送接口请求。
下面是一个简化版的替换headers参数,其中headers的值是前端传来的,replace是替换的的目标值,该变量值来自前端传来的变量。
headers = '{"Content-Type": "${appjson}", "token": "mkJihUPm6BTu6lepfmMo"}'
replace = {'appjson': 'application/json'}
s = Template(headers)
replace_header = s.safe_substitute(replace)
print(f'replace headers:{replace_header}')
运行上面的代码,headers中的值替换成功
replace headers:{"Content-Type": "application/json", "token": "mkJihUPm6BTu6lepfmMo"}