92

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?

lowerkey
  • 8,105
  • 17
  • 68
  • 102
  • 22
    You need to double all curly braces that should not be formatted. – Sven Marnach Mar 08 '12 at 18:52
  • 2
    Have you come across [multiline strings](http://docs.python.org/tutorial/introduction.html#strings)? If you use triple-quotes, you don't have to escape each newline. – Katriel Mar 08 '12 at 18:55
  • possible duplicate of [str.format() does not work, keyError](http://stackoverflow.com/questions/2755201/str-format-does-not-work-keyerror) – luator Sep 09 '15 at 12:41

1 Answers1

167

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.

kindall
  • 178,883
  • 35
  • 278
  • 309