String Splice Assignment

Skip Montanaro skip at
Tue Jul 17 00:56:04 CEST 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


    >>> a = 'asdf'
    >>> a = list(a)
    >>> a
    ['a', 's', 'd', 'f']
    >>> a[1:2] = ['EFGH']
    >>> a
    ['a', 'EFGH', 'd', 'f']
    >>> a = "".join(a)
    >>> a

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

More information about the Python-list mailing list