98

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:

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

Does someone know why?

2
  • 25
    You need to double all curly braces that should not be formatted. Commented Mar 8, 2012 at 18:52
  • 2
    Have you come across multiline strings? If you use triple-quotes, you don't have to escape each newline. Commented Mar 8, 2012 at 18:55

1 Answer 1

175

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Really helpful answer. Thank you for sharing this with everyone. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.