Pythonian string manipulation.

Emile van Sebille emile at fenx.com
Sat Jan 6 12:22:59 EST 2001


Strings are immutable.  You can extract string slices, but
not assign into them.  IIRC, Marc Lemburg offers text tools
that allow this, but I've not used them.  In normal python,
you must build a new string, and bind the variable to it.


>>> s = 'hello, world'
>>> l = s.split(', ')
>>> l.reverse()
>>> s = ', '.join(l)
>>> s
'world, hello'

HTH,

--

Emile van Sebille
emile at fenx.com
-------------------


<johnvert at my-deja.com> wrote in message
news:937if5$r9q$1 at nnrp1.deja.com...
> Hi,
>
> I was playing around with slices in Python (is that the
correct term?)
> and I tried, in order to switch the words `hello,' and
`world', to do:
>
> s = 'hello, world'
> l = s.find(',')
> s[0:l] = s[l + 1:]
>
> which in theory would seem to work, but I get the error:
>
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: object doesn't support slice assignment
>
> my two questions are: why isn't this allowed, and what is
the Pythonian
> way of doing this?
>
> Thanks,
>  -- John
>
>
> Sent via Deja.com
> http://www.deja.com/





More information about the Python-list mailing list