Multiple string.replace in one run

John Hunter jdhunter at
Fri Jun 20 14:50:05 CEST 2003

>>>>> "Thomas" == Thomas Güttler <guettler at> 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

    import re, sys
    s = """
      blu, blu

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

    def mysub(m):
        return vars[]
    # 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.

I have done a whole web site using YAPTU:

John Hunter

More information about the Python-list mailing list