import re
data = {
'name': 'gou',
'age': 18
}
def my_format(d: dict, s: str, repl: str) -> str:
r = re.findall(repl, s)
res = {'{{' + i + '}}': d[i] for i in r}
if len(res) < len(d):
raise ValueError(f'期待{len(res)}个参数,传了{len(d)}个')
ret = re.sub(repl, lambda item: str(res[item.group()]), s)
return ret
x = my_format(data, "My name is {{name}},{{name}},age is {{age}}", r'\{\{(.*?)\}\}')
print(x)
网友评论