[Tutor] append string

Andreas Kostyrka andreas at kostyrka.org
Sat Mar 22 09:46:58 CET 2008

somestring = "ABC"
somestring2 = somestring + "D"
somestring2 += "EF"

assert somestring2 == "ABCDEF"
assert somestring == "ABC"
assert id(somestring) != id(somestring2)

Basically, strings are immutable. If you need to append something to a
string, you need to construct a new string object with the new value.

Now if you are using this to collect huge outputfiles in pieces, one of
the common idioms in Python is collecting it in a list, and converting
to string at the end:

collector = []
for i in xrange(100000):
    collector.append((str(i) * 80)[0:80])

string = "".join(collector)
assert len(string) == 8000000 # ~8MB


Am Freitag, den 21.03.2008, 17:04 -0700 schrieb elis aeris:
> how do I append to the end of strings?
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Dies ist ein digital signierter Nachrichtenteil
Url : http://mail.python.org/pipermail/tutor/attachments/20080322/65f38dcb/attachment.pgp 

More information about the Tutor mailing list