Python 格式抛出 KeyError [英] Python format throws KeyError

查看:89
本文介绍了Python 格式抛出 KeyError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码片段:

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

抛出一个KeyError:

throws a KeyError:

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

有人知道为什么吗?

推荐答案

该代码中有许多未转义的大括号.Python 将所有大括号视为占位符,并试图将它们全部替换.但是,您只提供了一个值.

You have a number of unescaped braces in that code. Python considers all braces to be placeholders and is trying to substitute them all. 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.

这篇关于Python 格式抛出 KeyError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆