multiple replaces

H

Harald Armin Massa

again, and again ... another try of templating

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("%","%%")
h2=h1.replace("<!--tree-->","%(tree)s")
h3=h2.replace("<!--house-->","%(house)s")

house="something awfull"
tree="something beautifull"
print h3 % locals()


--> the <!--something--> approach allows it for me, that I can write
real HTML which looks fair. The replacing-chain takes care of % signs
within the file, and also makes a template for string replaces

BUT... it looks terribly inefficient to me. There are 3 strings which
are only there to be garbage collected. I am looking for a speedy way
of
"go through the text, and if you find sth. that is in REPLACEMENT,
replace it with it"

sth. like
rpdict={"<!--tree-->":"%(tree)s","<!--house-->":"%(house)s","%","%%"}

for key, value in rpdict.iteritems():
h1=h1.replace(key, value)

but ... without the garbage, in one command.

I guess there are very, very, very wise solution for this problem, but
I do not know of them.

Who knows and tells me?

Harald
 
D

D H

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()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,521
Members
44,995
Latest member
PinupduzSap

Latest Threads

Top