Python 从字符串中查找和替换唯一键语法

c.g*_*rey 1 python python-3.x

我得到了一个带有预定义变量的 HTML 模板。我想给变量赋值。

我的模板:

temp_string = """<td style="font-size:18px;">Dear {{var:name:"user"}}, welcome and congratulations on joining stack. Your age is {{var:age:"0"}}</td></tr>"""
Run Code Online (Sandbox Code Playgroud)

我的字典:

my_data = {'name': 'Foo', 'age': 20}
Run Code Online (Sandbox Code Playgroud)

最终输出

"""<td style="font-size:18px;">Dear Foo, welcome and congratulations on joining stack. Your age is 20</td></tr>"""
Run Code Online (Sandbox Code Playgroud)

我的代码

>>> temp_string = """<td style="font-size:18px;">Dear {{var:name:"user"}}, welcome and congratulations on joining stack. Your age is {{var:age:"0"}}</td></tr>"""
>>> my_data = {'name': 'Foo', 'age': 20}
>>> for key,value in my_data.items():
...     if key in temp_string:
...             temp_string.replace(key, value)
Run Code Online (Sandbox Code Playgroud)

AKX*_*AKX 5

干得好...

  • 正如评论中提到的,re.sub()有一个表单接受一个函数,该函数将返回给定匹配对象的替换值。
    • 我们检查占位符(捕获组 1)的内容是否以 开头var:,然后将其拆分为三个部分(最多拆分为 2 个拆分)。
    • 如果占位符不以 开头var:,则逐字传递。您可能想要引发错误。
  • 由于默认值似乎被引用,我们使用取消引用ast.literal_eval()它们。
import re
import ast


def replace_placeholders(template, data):
    def replacer(match):
        content = match.group(1)
        if content.startswith("var:"):
            _, name, quoted_default = content.split(":", 2)
            if name in data:
                return str(data[name])
            return str(ast.literal_eval(quoted_default))
        # Pass other content through as-is
        return match.group(0)

    return re.sub(r"{{(.+?)}}", replacer, template)


print(
    replace_placeholders(
        template="""Dear {{var:name:"user"}}, welcome and congratulations on joining stack. Your age is {{var:age:"0"}}""",
        data={"name": "Foo", "age": 20},
    )
)
Run Code Online (Sandbox Code Playgroud)