简体   繁体   English

Python 格式抛出 KeyError

[英]Python format throws KeyError

The following code snippet:以下代码片段:

template = "\                                                                                
function routes(app, model){\                                                                
  app.get('/preNew{className}', function(req, res){\                                         
    res.render('{className}'.ejs, {});\                                                      
  });\                                                                                       
});".format(className=className)

throws a KeyError:抛出一个 KeyError:

Traceback (most recent call last):   File "createController.py", line 31, in <module>
    });".format(className=className) KeyError: '  app'

Does someone know why?有人知道为什么吗?

You have a number of unescaped braces in that code.您在该代码中有许多未转义的大括号。 Python considers all braces to be placeholders and is trying to substitute them all. Python 将所有大括号视为占位符,并试图将它们全部替换。 However, you have only supplied one value.但是,您只提供了一个值。

I expect that you don't want all your braces to be placeholders, so you should double the ones that you don't want substituted.我希望您不希望所有的大括号都成为占位符,因此您应该将不想替换的大括号加倍。 Such as:如:

template = """                                                                  
function routes(app, model){{
  app.get('/preNew{className}', function(req, res){{
    res.render('{className}'.ejs, {{}});                                           
  }};                                                      
}});""".format(className=className)

I also took the liberty of using triple quotes for the string literal so you don't need the backslashes at the end of each line.我还冒昧地为字符串文字使用了三重引号,因此您不需要在每行末尾使用反斜杠。

Well, just another way of doing this without format could be:好吧,另一种没有format可能是:

In [1673]: className = 'myclass'                                                                                                                                                                            

In [1674]: template = 'function routes(app, model){app.get("/preNew"{'+className+'}, function(req, res){res.render({"'+className+'".ejs, {});});});'                                                        

In [1675]: template                                                                                                                                                                                         
Out[1675]: 'function routes(app, model){app.get("/preNew"{myclass}, function(req, res){res.render({"myclass".ejs, {});});});'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM