By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,095 Members | 1,586 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,095 IT Pros & Developers. It's quick & easy.

multiple replaces

P: n/a
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

Sep 16 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Harald Armin Massa wrote:
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.


http://effbot.org/zone/python-replace.htm

</F>

Sep 16 '05 #2

P: n/a
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()

Sep 16 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.