Python模板字符串Template如:${变量名称}

发布时间 2023-10-11 12:19:00作者: 公子Learningcarer
1.概述
如果你在操作字符串,如果你操作的字符串内容很多,希望字符串中的内容能够根据规则动态替换,并且在长篇幅的字符串中需要替换任意位置任意次数的字符,使用str提供的replace方法代码会写的非常复杂,且出错不易排查。
在这个场景中试试Template类把,他能够创建一个模板替换字符串。
 

1.1Template类替换字符串基本操作

1.替换字符串内容并且输出字符串中不存在得字符
import json
import re
from string import Template
# 将list格式的测试用例转化为 字符串格式
test_data = json.dumps(yuan, ensure_ascii=False)

dict_data = {
    "num": 123,
    "name": '李四'
}
# 使用Template模板类 进行数据替换
test_data = Template(test_data).safe_substitute(dict_data)
# 使用函数值 替换 字符串中的 函数
for fun in re.findall('\\${(.*?)}', test_data):
    print(fun)
    try:
        test_data = test_data.replace('${%s}' % fun, exec(f"result = {fun}"))
    except Exception as e:
        print(e)
# 将 字符串 转化为 list
test_data = json.loads(test_data)
print(test_data)
print(type(test_data))
结果
a_b()
name 'a_b' is not defined
uuu
name 'uuu' is not defined
[{"ID": 1, "title": "\u65b0\u589e\u5e73\u53f0\u836f\u54c1", "data": "{\"a_b\":\"qqq${a_b()}\",\"condition.baseunit\":\"\u674e\u56db\",\"condition.name\":\"\u6d4b\u8bd5\u996e\u7247123\",\"b_d\":\"${uuu}\"}", "expected_data": "{\"code\":0,\"message\":\"\u6dfb\u52a0\u6210\u529f\uff01\",\"object\":null}", "extract_data": null, "assert_db": null}]
<class 'str'>
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模板中需要批量替换多个变量,可以使用字典批量传递数据。
 
from string import Template

s1 = "我在用 ${code} ${num} 开发项目"
data = {
   'code':'python',
   'num': 3
   }
s = Template(s1)

print(s.safe_substitute(data))
2.3.自定义替换字符串符号
如果你不想使用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 开发项目
 
使用自定义的替换字符串符号,替换字符串结果:我在用 Python 3 开发项目
1
2.4.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_header:{"Content-Type": "application/json", "token": "mkJihUPm6BTu6lepfmMo"}