You can use python's re.sub function. But also look into full fledged template engines like Cheetah. import re txt=""" <html> <body> <p>whatever</p> <!--tree--> <p>the machine with bing</p> <!--house--> <p>10% of boo is foo</p> </html>""" h1=txt.replace("%","%%") h3 = re.sub("<!--(\w+)-->", "%(\\1)s", h1) house="something awfull" tree="something beautifull" print h3 % locals()