Question

I try to substitue strings with variables using locals() in python but I can find a way to use the % character inside the string without error. Here is a concrete example :

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

Result : TypeError: not enough arguments for format string

The problem is the % character in 100%. How can I escape it?

Was it helpful?

Solution

escape % with %

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

OTHER TIPS

Virhilo has already answered your direct question, but if you find you are building quite big/complicated templates it might be worth looking at a full blown template engine instead:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top