2

我正在尝试对 html/javascript 模板进行一些字符串替换,但是当页面字符串变量在代码中有一个大括号时,我收到“ValueError:不支持的格式字符'}'(0x7d)”的错误。如果我没有任何字符串替换,一切正常。谢谢阅读!

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)
4

1 回答 1

4

您的“模板”包含字符串% }(紧随其后100),python 将其解释为格式化指令。

%将百分比字符加倍%%,它会起作用。

>>> 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    '

或者,对不太容易出现此类问题的格式使用较新的.format()方法,尽管在这种特定情况下会挂在{ height: 100% }花括号对上,因此您的里程可能会发生很大变化;您必须将它们加倍(所以{{ height: 100% }})。

于 2012-09-07T09:04:28.097 回答