[英]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.