字符串替换-不支持格式字符'}'

String substitution - unsupported format character '}'

本文关键字:字符 格式 替换 不支持 字符串      更新时间:2023-09-26

我正在尝试对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)

您的"template"包含字符串% }(就在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% }})。