replace string patern with different value

Paul McGuire ptmcg at austin.rr.com
Mon May 9 11:49:54 EDT 2005


Well, not to be left out, here is a pyparsing solution.  But this looks
suspiciously like some form of mail-merge or templating application.
Google for 'python templating' for existing approaches to this problem.

Interestingly, using an iterator of L sidesteps a number of other
problems.  My original brute force version just used curelem as an
integer index into L, which required
1. a global declaration of curelem in replString
2. a separate variable to store the current element
3. a second command to increment curelem after saving the current
element
Changing curelem to be an iterator on the L list allowed me to collapse
all that junk down to a simple return statement, with no loss in
readability or maintainability.

-- Paul


from pyparsing import Literal
source = 'kode1 bla bla kode1 bla kode1'
L = [11,22,33]
curelem = iter(L)

def replString(st,loc,toks):
    return str( curelem.next() )

kode = Literal("kode1").setParseAction( replString )
newsource = kode.transformString( source )
print newsource

prints:
11 bla bla 22 bla 33




More information about the Python-list mailing list