Python format throws KeyError

前端 未结 2 599
旧巷少年郎
旧巷少年郎 2020-11-28 08:12

The following code snippet:

template = \"\\                                                                                
function routes(app, model){\\            


        
相关标签:
2条回答
  • 2020-11-28 08:56

    Well, just another way of doing this without format could be:

    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, {});});});'
    
    0 讨论(0)
  • 2020-11-28 09:00

    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.

    0 讨论(0)
提交回复
热议问题