if statements

Skip Montanaro skip at pobox.com
Fri Jan 18 20:56:15 CET 2002


    >> xmlstr = "<?xml version='1.0'?>"
    >> xmlstr = xmlstr +"<config"
    >> xmlstr = xmlstr +"last_server=\"0\""

    Alex> Don't do that.  That's wasting a LOT of performance.  NEVER build
    Alex> up a big string with a zillion s = s + ... (or s += ... which
    Alex> turns out to be the same thing).  You could do:

    Alex>     xmlstr = ( "<?xml version='1.0'?>"
    Alex>         + "<config"
    Alex>         + "last_server=\"0\""

    Alex> and so on, just close the ) when done to terminate the logical
    Alex> line.

I suspect Alex intended to delete the plus signs.  As long as what you want
to concatenate are a bunch of string literals, just placing them next to one
another (token-wise) is sufficient.  They are collapsed at compile time:

    xmlstr = ( "<?xml version='1.0'?>"
               "<config"
               " last_server=\"0\"")

A space after "<config" probably also useful in this particular context,
otherwise you'll wind up with

    <?xml version='1.0'?><configlast_server="0"

Finally, since there are four possibilities for string quotes, you should
rarely need to actually escape a quote inside a string literal.  Just choose
your quotes appropriate to the string's content:

    xmlstr = ( "<?xml version='1.0'?>"
               "<config"
               ' last_server="0"')

-- 
Skip Montanaro (skip at pobox.com - http://www.mojam.com/)




More information about the Python-list mailing list