Multiple string.replace in one run

Thomas Bellman bellman at
Fri Jun 20 21:43:29 CEST 2003

Thomas Güttler <guettler at> wrote:

> Hi!

> I want to replace strings in a file:
>  $VAR$ should be replaced with "foo".

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

Are you tied to this particular syntax, or can you choose any you
want?  You might consider using "%(VAR)s" instead; then you can
use the % operator to get the behaviour you want:

    s = """\
     <head> <title>%(TITLE)s</title> </head>
     <body> %(TITLE)s
     %(TABLE_overview)s blu, blu </body>

    print s % {"TITLE": "my title", "TABLE_overview": "Look"}


     <head> <title>my title</title> </head>
     <body> my title
     Look blu, blu </body>

However, I should not that my own experience using this is that
it is a bit error prone; it is very easy to forget the trailing
"s" after the variable name when writing your text/HTML/whatever

Thomas Bellman,   Lysator Computer Club,   Linköping University,  Sweden
"Beware of bugs in the above code; I have    !  bellman @
 only proved it correct, not tried it."      !  Make Love -- Nicht Wahr!

More information about the Python-list mailing list