1

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%の%文字です。どうすればそれを逃れることができますか?

4

2 に答える 2

4

% を % でエスケープする

html = """<html><head>
<style>#square{color:%(color)s;width:100%%;height:100%%;}</style>    
</head>    <body>  <div id="square">  </div>
</body></html>""" % locals()
于 2011-01-19T20:44:57.777 に答える
1

Virhilo はすでにあなたの直接の質問に答えていますが、非常に大きく複雑なテンプレートを作成している場合は、代わりに本格的なテンプレート エンジンを検討する価値があるかもしれません。

于 2011-01-19T20:48:36.150 に答える