[英]String substitution - unsupported format character '}'
我正在尝试为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)
您的“模板”包含字符串% }
(紧随其后的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% }}
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.