实现字符串展位替换

2020-11-07  本文已影响0人  领带衬有黄金
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)

上一篇下一篇

猜你喜欢

热点阅读