Help, Search and Substitute

Olivier Dagenais olivierS.dagenaisP at canadaA.comM
Thu Nov 2 16:45:21 EST 2000


I'd say it depends on how big your templates are going to be.  If they are
small, you can probably just do a bunch of string.replace calls and the
overhead won't be noticeable:

# pseudo-code!
filledOut = template_test
for key in template_vals.keys():
    filledOut = string.replace ( filledOut, '{' + key + '}',
template_vals[key] )


If, however, you have a large template, all those replaces might take a lot
of memory, since a new string is created each time and I don't think the
memory gets deallocated right away.

Another thing to try is to write a parser, that looks at the source
character by character, appending to a list/tuple, remembers when a '{' is
encountered (suspends the appending) and when a '}' is encountered, it does
the lookup and appends the result.  Then you join all your list elements
together to form the filled-out string.

Does it help?

--
----------------------------------------------------------------------
Olivier A. Dagenais - Software Architect and Developer
"Someone called 'Type your name here' is impersonating me on the
internet and is posting exactly the same things I am posting!"


"Pete Shinners" <pete at visionart.com> wrote in message
news:8tcp98$t79$1 at la-mail4.digilink.net...
> I've got to write a search and replace type routine that
> works on a template file. i have a dictionary with string
> keys and values. i want parse a template file and replace
> "{KEYNAME}" with the value of KEYNAME from my dictionary.
>
> i'm guessing this is where the reg-exp's come in to play?
> i assume it's time i sit down and get the basics on these?
>
> i've already written this, which handles the case with
> TEMPLATE:KEYNAME on its own line, but i need to upgrade
> it to substitute things out in mid-line
>
>
> >>> template_test = "This {NOUN} is {ADJECTIVE}!"
> >>> template_vals = {"NOUN":"parrot", "ADJECTIVE":"dead"}
> >>> print template_substitute(template_test, template_vals)
> "This parrot is dead!"
>
> now i just need someone to help me write the substitute
> function. any pointers on this? help is appreciated
>
>
>
>





More information about the Python-list mailing list