“%”字符导致用locals()替换字符串时出错

2024-04-23 06:06:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在python中使用locals()来替换字符串,但是我可以找到一种方法来使用字符串中的%字符而不会出错。下面是一个具体的例子:

color = colors_generator() #the function return a color

html = """<html><head>
<style>#square{color:%(color)s;width:100%;height:100%;}</style>    
</head>    <body>  <div id="square">  </div>
</body></html>""" % locals()

print "Content-Type: text/html\n"    
print html

结果:TypeError: not enough arguments for format string

问题是100%中的%字符。我怎么才能逃脱呢?在


Tags: 方法字符串divstylehtmlbody字符generator
2条回答

Virhilo已经回答了您的直接问题,但是如果您发现您正在构建相当大/复杂的模板,那么您可能需要查看一个完整的模板引擎:

用%转义%

html = """<html><head>
<style>#square{color:%(color)s;width:100%%;height:100%%;}</style>    
</head>    <body>  <div id="square">  </div>
</body></html>""" % locals()

相关问题 更多 >