from string import Template
import json
class ReplaceTepmlate(Template):
delimiter ="${}"
def test_example1():
a={"a":[{"c":1,‘b‘:‘${env}‘},{"c":"${ip}"}]}
string_text=json.dumps(a)
# will replace like this {"a": [{"c": 1, "b": "litao"}, {"c": "10"}]}
print(Template(string_text).substitute({"env":"litao","ip":10}))
class TemplateUserDefine(Template):
delimiter = ‘$‘
def test_example2():
""" test $$env replace escape,$$不替换"""
b={"test":11,‘array‘:{"data":["hello",‘$name‘],"error":{"email":‘$$env‘}}}
s=json.dumps(b)
# will not replace $$env it keep self $env
#{"test": 11, "array": {"data": ["hello", "zhangsan"], "error": {"email": "$env"}}}
print(TemplateUserDefine(s).substitute({"name":‘zhangsan‘,"env":111}))
class TemplateSpecial(Template):
delimiter = ‘#‘
def test_example3():
# test # define variable replace
test=‘hello,#var,i test args replace instead of kwargs .‘
ret=TemplateSpecial(test).substitute(var=111)
# hello,111,i test args replace instead of kwargs .
print(ret)
if __name__ == ‘__main__‘:
test_example2()
# 优雅的合并dict
foo=dict(a=1,b=2)
bar=dict(key="value")
# you will get {‘a‘: 1, ‘b‘: 2, ‘key‘: ‘value‘}
print({**foo,**bar})
python string.Template 实现$var,${var} ,#var替换,比如接口实现参数化
原文:https://www.cnblogs.com/SunshineKimi/p/13991763.html