idiom: concatenate strings with separator
Christian Tanzer
tanzer at swing.co.at
Thu May 3 08:01:43 EDT 2001
> Harald Kirsch <kirschh at lionbioscience.com> wote:
>
> Recently I started using code like this
>
> l = []
> for x in somethings:
> y = massage(x)
> l.append(y)
>
> return string.join(y, my_favorite_separator)
>
>
> to produce strings made of substrings separated by something. Note
> that with immediate string concatenation its hard to avoid the
> separator either in front or at the end of the produced string.
>
> Nevertheless I wonder if something like
>
> s = ""
> sep = ""
> for x in somethings:
> y = massage(x)
> s = s + sep + y
> sep = my_favorite_separator
>
> return s
>
> is faster or uses less memory than the previous solution.
In general, the repeated string concatenation will be much slower --
each execution of `s = s + sep + y' copies `s' and discards the old
copy of `s'. For a few short strings it might not matter much, though.
BTW, timing the alternatives yourself is very easy -- see the standard
modules time and profile. Measuring performance is much more reliable
than guessing. Having usenetters guess might be even worse <wink>.
--
Christian Tanzer tanzer at swing.co.at
Glasauergasse 32 Tel: +43 1 876 62 36
A-1130 Vienna, Austria Fax: +43 1 877 66 92
More information about the Python-list
mailing list