String Splice Assignment
Skip Montanaro
skip at pobox.com
Mon Jul 16 18:56:04 EDT 2001
nathan> Why don't strings support splice assignment, and what are some
nathan> alternatives?
Strings are immutable. Try:
>>> a = 'asdf'
>>> a = a[0:1] + 'EFGH' + a[2:]
>>> a
'aEFGHdf'
or
>>> a = 'asdf'
>>> a = list(a)
>>> a
['a', 's', 'd', 'f']
>>> a[1:2] = ['EFGH']
>>> a
['a', 'EFGH', 'd', 'f']
>>> a = "".join(a)
>>> a
'aEFGHdf'
If you want to do lots of operations efficiently, the list variant may be
more efficient assuming you leave it in list form for quite awhile and don't
constantly convert back to the string form.
--
Skip Montanaro (skip at pobox.com)
http://www.mojam.com/
http://www.musi-cal.com/
More information about the Python-list
mailing list