idiom: concatenate strings with separator
M.-A. Lemburg
mal at lemburg.com
Thu May 3 13:11:26 EDT 2001
Harald Kirsch wrote:
>
> 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.
The fastest and most memory efficient solution is probably
using cStringIO:
import cStringIO
sep = "-"
temp = cStringIO.StringIO()
write = temp.write
for x in items:
write(sep)
write(x)
temp.seek(len(sep))
return temp.read()
PS: But Lutz Ehrlich would have told you that too ;-)
--
Marc-Andre Lemburg
______________________________________________________________________
Company & Consulting: http://www.egenix.com/
Python Software: http://www.lemburg.com/python/
More information about the Python-list
mailing list