您当前的位置: 首页 >  Python

彭世瑜

暂无认证

  • 1浏览

    0关注

    2791博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Python:正则re.sub实现简易的模板引擎

彭世瑜 发布时间:2020-12-31 22:22:32 ,浏览量:1

代码实现

# -*- coding: utf-8 -*-
import re


class Template(object):
    pattern = r"\{(\w+)\}"

    def __init__(self, template):
        self.template = template
        self.re_pattern = re.compile(self.pattern)

    def compile(self, **kwargs):
        def foo(mo):
            return kwargs[mo.group(1)]

        return self.re_pattern.sub(foo, self.template)


if __name__ == '__main__':
    t = Template('/student/{uid}/{name}')

    data = {
        "uid": '1',
        "name": "Tom"
    }

    print(t.compile(**data))
    # /student/1/Tom

关注
打赏
1665367115
查看更多评论
立即登录/注册

微信扫码登录

0.1513s