Python字符串格式化引发KeyError错误

4
这个问题之前已经有人回答过了,但我的字符串中没有任何额外的花括号来破坏格式,所以我完全不知道这个错误为什么会出现。错误是关键字错误:content。
html = """
    <table class=\"ui celled compact table\" model=\"{model}\">
        {theaders}
        <tbody>
            {content}
        </tbody>
    </table>
    """
html = html.format(model=model)
html = html.format(content=data)
html = html.format(theaders=theaders)

2
附注: 在这个例子中,反斜杠是不必要的。三引号字符串的好处之一是任何单个引号字符都不再是特殊字符。 - Robᵩ
我只是在尝试找出错误的过程中完成了它们 :) - Mojimi
2个回答

10

你可以使用字典逐行处理,并通过**将字典作为关键字参数传递。

d=dict()
d['model']=model
d['content']=data
d['theaders']=theaders

html = html.format(**d)

7

您需要一次性填写完所有值:

html.format(model=model, content=data, theaders=theaders)

1
@Mojimi 不能直接使用 str.format() 实现此功能。模板字符串 可以使用 safe_substitute() 实现,但是占位符语法不同。但是你为什么需要它呢? - dhke
1
是的,你可以这样做。你需要用双括号将 content 包围起来;用四个括号({model}...{{content}}..{{{{theaders}}}})将 theaders 包围起来。这有点像一个 hack... - hiro protagonist
@Mojimi Template.safe_substitute()Template.substitute()返回一个字符串(其中变量已替换)。原始字符串必须传递给模板,所以我不太清楚你在问什么。 - dhke
@dhke 但如果它返回一个字符串而不是模板,我该如何逐步操作? - Mojimi
2
@Mojimi html = Template(html).safe_substitute(model=model); html = Template(html).safe_substitute(content=data)。但我真的建议采用@jean-françois-fabre答案中的方法。 - dhke
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接