Pythonian string manipulation.
Aahz Maruch
aahz at panix.com
Sat Jan 6 12:19:10 EST 2001
In article <937if5$r9q$1 at nnrp1.deja.com>, <johnvert at my-deja.com> wrote:
>
>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?
Strings are immutable, so you can't assign to a slice. Here's what I'd
do:
s = 'hello, world'
l = s.split(', ')
l.reverse()
s = string.join(l, ', ')
(I'm assuming you're using Python 2.0 because of the s.find())
--
--- Aahz (Copyright 2000 by aahz at pobox.com)
Androgynous poly kinky vanilla queer het <*> http://www.rahul.net/aahz/
Hugs and backrubs -- I break Rule 6
"This is Usenet. We're all masturbating in public places." -DH
More information about the Python-list
mailing list