我有一堆f字串作为打印标签的模板.这些F-STING中的占位符将填充标签的条目.该F形字符串的一部分可能如下所示:

template_1 = f"""
^FH\^FDLA,{identifier}^FS
^FT145,51FD{name}^FS^CI27
"""

对于每个字段(在本例中为IDENTIFIER和NAME),如果没有提供值,我需要缺省值.这些默认设置对于每个标签都不相同,即使它们具有相同的变量名.

目前,我能想到的唯一(丑陋的)解决方案是使用if/Else语句来设置缺省值,然后对f字符串使用一个巨大的字典.这可能看起来像这样(在某些函数中):

if template == "template_1":
    if name is None:
        name = "name"
    if project is None:
        project= "project"
elif template == "template_2":
    if name is None:
        name = "different name"
    if person is None:
        person = "some person"

temmplates = {
    "template_1" : f"""
    as{name}{project}
    """,
    "template_2" : f"""
    asflkjasdf{person}{name}
    """,
}

必须有一种更好的方法来动态地用值填充一些f-ing模板并为其提供缺省值.也许是用一个类或者别的什么?但我就是想不通.最好的好处是,如果我可以将这些f-stings和默认值存储在一个toml文件中,但一次只有一个问题:)

提前谢谢你!

推荐答案

这就是你想要的吗?

class Template:
    def __init__(self, template_string, defaults):
        self.template_string = template_string
        self.defaults = defaults

    def render(self, **kwargs):
        context = {**self.defaults, **kwargs}
        return self.template_string.format(**context)


templates = {
    "template_1": Template("^FH\^FDLA,{identifier}^FS\n^FT145,51FD{name}^FS^CI27", {"name": "name", "project": "project"}),
    "template_2": Template("asflkjasdf{person}{name}", {"name": "different name", "person": "some person"})
}

template = templates["template_1"]
rendered_label = template.render(identifier="ID123", name="John Doe")
print(rendered_label)

Python相关问答推荐

如何将uint 16表示为float 16

如何使用函数正确索引收件箱?

如何知道标志是否由用户传递或具有默认值?

如何将桌子刮成带有Se的筷子/要求/Beautiful Soup ?

覆盖Django rest响应,仅返回PK

拆分pandas列并创建包含这些拆分值计数的新列

使用pandas、matplotlib和Yearbox绘制时显示错误的年份

如何在BeautifulSoup中链接Find()方法并处理无?

更改matplotlib彩色条的字体并勾选标签?

如何让剧作家等待Python中出现特定cookie(然后返回它)?

Python解析整数格式说明符的规则?

如何在给定的条件下使numpy数组的计算速度最快?

梯度下降:简化要素集的运行时间比原始要素集长

cv2.matchTemplate函数匹配失败

导入...从...混乱

什么是最好的方法来切割一个相框到一个面具的第一个实例?

如何在turtle中不使用write()来绘制填充字母(例如OEG)

如何在Python中获取`Genericums`超级类型?

如果初始groupby找不到满足掩码条件的第一行,我如何更改groupby列,以找到它?

在Python中使用yaml渲染(多行字符串)