Multiple string.replace in one run

John Hunter jdhunter at ace.bsd.uchicago.edu
Fri Jun 20 08:50:05 EDT 2003


>>>>> "Thomas" == Thomas Güttler <guettler at thomas-guettler.de> writes:

    Thomas> I could do this with string.replace, but if I want to
    Thomas> replace several variables, I need to do the replace
    Thomas> several times. Since the file could be very long I am
    Thomas> searching for a better solution.

    Thomas> How can I replace several variables at once?

The variable delimiters, eg, '$', were used inconsistently in the
example you posted (sometimes you had them before and after the token,
sometimes just before).  If they are regular enough in your text file
to use a regular expression, you can use the re.sub method with a
function

    import re, sys
    s = """
    <html>
     <head>
      <title>$TITLE$</title>
     </head>
     <body>
      $TITLE$
      $TABLE_overview$
      blu, blu
     </body>
    </html> 
    """

    vars = {'$TITLE$' : 'my title', 	
            '$TABLE_overview$' : 'Look'}	

    def mysub(m):
        return vars[m.group(0)]
        
    # a literal dollar sign, followed by anything that isn't a dollar
    # sign followed by a literal dollar sign
    print re.sub('\$[^$]+\$', mysub, s)  

Note that there are some very good python html templating utilities
out there, like YAPTU, which is just 78 lines python and powerful
enough not only to allow you to use tokens as above, but also to
embed python expression, loops, conditions, etc, in your html.

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52305

I have done a whole web site using YAPTU:
http://matplotlib.sourceforge.net/

John Hunter





More information about the Python-list mailing list