Python格式引发KeyError
发布于 2021-01-29 19:29:21
以下代码段:
template = "\
function routes(app, model){\
app.get('/preNew{className}', function(req, res){\
res.render('{className}'.ejs, {});\
});\
});".format(className=className)
抛出KeyError:
Traceback (most recent call last): File "createController.py", line 31, in <module>
});".format(className=className) KeyError: ' app'
有人知道为什么吗?
关注者
0
被浏览
44
1 个回答
-
该代码中有许多未转义的花括号。Python认为所有花括号都是占位符,并正在尝试替换所有花括号。但是,您只提供了一个值。
我希望您不希望所有的花括号都成为占位符,因此您应该将不希望使用的花括号加倍。如:
template = """ function routes(app, model){{ app.get('/preNew{className}', function(req, res){{ res.render('{className}'.ejs, {{}}); }}; }});""".format(className=className)
我还随意使用字符串文字的三引号,因此您无需在每行末尾使用反斜杠。