简体   繁体   中英

String substitution - unsupported format character '}'

I'm trying to do some string substitution for html/javascript templating, however when the page string variable has a curly brace in the code, I get the error of "ValueError: unsupported format character '}' (0x7d)". If I don't have any string substitution everything works fine. Thanks for reading!

import webapp2
page = """
<html>
    <style type="text/css">
      html { height: 100% }
      body { height: 100%; margin: 0; padding: 0 }
      #map_canvas { height: 100% }
    </style>
    %(say)s
</html>
    """

class MainHandler(webapp2.RequestHandler):
    def write_form(self, say):
        self.response.out.write(page % { "say": say })

    def get(self):
        self.write_form("hello")

app = webapp2.WSGIApplication([('/', MainHandler)],
                              debug=True)

Your 'template' contains the string % } (right after the 100 there), and python is interpreting that as a formatting instruction.

Double the % percent characters to %% and it'll work.

>>> page = """
... <html>
...     <style type="text/css">
...       html { height: 100%% }
...       body { height: 100%%; margin: 0; padding: 0 }
...       #map_canvas { height: 100%% }
...     </style>
...     %(say)s
... </html>
...     """
>>> page % dict(say='foo')
'\n<html>\n    <style type="text/css">\n      html { height: 100% }\n      body { height: 100%; margin: 0; padding: 0 }\n      #map_canvas { height: 100% }\n    </style>\n    foo\n</html>\n    '

Alternatively, use the newer .format() method for a format less prone to such problems, although in this specific case that'll get hung up on the { height: 100% } curly braces pairs, so your mileage may very well vary; you'd have to double those instead (so {{ height: 100% }} ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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