String Splice Assignment

Quinn Dunkan quinn at yak.ugcs.caltech.edu
Mon Jul 16 19:06:58 EDT 2001


On 16 Jul 2001 14:57:06 -0700, eAndroid <gervaserules at yahoo.com> wrote:
>Why don't strings support splice assignment, and what are some

Because strings are immutable.

>alternatives?

Make a new string:

>>>> a = 'asdf'
>>>> a[1:2] = "EFGH"
>>>> a
>'aEFGHf'

a = 'aoeu'
b = a[:1] + 'HTNS' + a[2:]
b #-> 'aHTNSeu'

(note that even were strings mutable, your above code would not produce
'aEFGHf' since a[1:2] addresses a single character)

or:

a.replace('o', 'HTNS')


Check the docs for the string module for more.



>I have a long string (~1000 chars) that I would like to do multiple
>splice assignments on. I am now interested alternatives to do this,
>especially efficient ones.

1000 bytes is not a long string.  Go ahead and make copies.  And now is not
the time to make sacrifices to the tin god efficiency.

If some day you do have a really long string (say, 1 million characters), you
can break it up into chunks and store the chunks in a list.  When you want the
whole thing you use string.join.



More information about the Python-list mailing list