【问题标题】:"%" character cause Error in strings substitution with locals()“%”字符导致用 locals() 替换字符串时出错
【发布时间】:2011-01-19 20:43:18
【问题描述】:

我尝试在 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% 中的 % 字符。我怎么能逃脱它?

【问题讨论】:

    标签: python locals string-substitution


    【解决方案1】:

    用 % 转义 %

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

    【讨论】:

      【解决方案2】:

      Virhilo 已经回答了您的直接问题,但是如果您发现自己正在构建相当大/复杂的模板,则可能值得研究一个完整的模板引擎:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多