Skip to main content
 首页 » 编程设计

python之扩展 Python 模板字符串

2025年01月19日31qlqwjy

是否可以扩展 Template strings所以我可以向标识符添加方法:

默认情况下我可以替换简单变量:

from string import Template 
t = Template("${noun}ification") 
t.substitute(dict(noun='Egg'))  # Output: 'Eggification' 

但我希望使用自定义方法(例如 as_b)扩展标识符:

t = Template("${noun.as_b}ification")  # Desired output: '<b>Egg</b>ification' 

我知道我可以很容易地用 Formatted string literals 做类似的事情但是是否可以像上面那样使用模板字符串? 我不能使用格式化字符串文字,因为它在脚本、JSON 文件或任何包含花括号的文本中不起作用。

本质上,我正在寻找可以在格式化字符串文字灵 active 中提供模板字符串语法的东西。

请您参考如下方法:

不是直接的答案,但我建议不要使用模板字符串。

如果您使用的是 Python 3.6 或更新版本,请使用 f-strings:

def bold(t): 
    return f"<b>{t}</b>" 
 
noun = 'Egg' 
 
print(f"{bold(noun)}ification") 

运行时:

<b>Egg</b>ification 

如果你更喜欢更强大的模板机制,我强烈推荐Jinja2 .