Multiple string.replace in one run

Thomas Bellman bellman at lysator.liu.se
Fri Jun 20 21:43:29 CEST 2003


Thomas Güttler <guettler at thomas-guettler.de> 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 = """\
    <html>
     <head> <title>%(TITLE)s</title> </head>
     <body> %(TITLE)s
     %(TABLE_overview)s blu, blu </body>
    </html>
    """

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

gives:

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

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
files.


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




More information about the Python-list mailing list