You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python字符串模板中为未指定变量设置默认值?

解决方案

方案一:自定义Template类(推荐)

继承string.Template,通过重写safe_substitute方法,自动为所有未传入的变量设置空字符串默认值。这个方案利用原生模板的解析逻辑,能准确识别所有合法变量(包括$var和${var}两种形式),兼容性最好。

from string import Template

class DefaultTemplate(Template):
    def safe_substitute(self, **kwargs):
        # 获取模板中所有定义的变量标识符
        all_vars = self.get_identifiers()
        # 初始化默认字典,所有变量默认值为空字符串
        default_dict = {var: '' for var in all_vars}
        # 用用户传入的变量覆盖默认值
        default_dict.update(kwargs)
        # 调用父类的方法完成替换
        return super().safe_substitute(default_dict)

# 测试示例
template = DefaultTemplate('$a ${b} $c $$d')
# 只传入a的值,b和c会被替换为空,$$d保留为$d
print(template.safe_substitute(a='hello'))  # 输出: hello   $d

方案二:正则替换处理结果

如果不想自定义类,可以先通过safe_substitute得到部分替换的结果,再用正则表达式把剩余未替换的变量占位符替换为空字符串。需要注意处理转义的$$(会被原生模板转为$),避免误替换。

import re
from string import Template

def substitute_with_default(template_str, **kwargs):
    temp = Template(template_str)
    partial_result = temp.safe_substitute(**kwargs)
    # 匹配未被替换的$var和${var},排除前面有$的转义情况
    pattern = r'(?<!\$)\$(?:\{([a-zA-Z_][a-zA-Z0-9_]*)\}|([a-zA-Z_][a-zA-Z0-9_]*))'
    return re.sub(pattern, '', partial_result)

# 测试示例
print(substitute_with_default('$a ${b} $c $$d', a='hello'))  # 输出: hello   $d

两个方案都属于轻量级实现,不需要额外依赖第三方库,完全满足你的需求。

内容的提问来源于stack exchange,提问作者link89

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 12:20:16