Reputation:
I want to change the value of a particular string index, but unfortunately
string[4] = "a"
raises a TypeError
, because strings are immutable ("item assignment is not supported").
So instead I use the rather clumsy
string = string[:4] + "a" + string[4:]
Is there a better way of doing this?
Upvotes: 6
Views: 960
Reputation: 273416
The strings in Python are immutable, just like numbers and tuples. This means that you can create them, move them around, but not change them. Why is this so ? For a few reasons (you can find a better discussion online):
If you look around the Python web a little, you’ll notice that the most frequent advice to "how to change my string" is "design your code so that you won’t have to change it". Fair enough, but what other options are there ? Here are a few:
Plagiarized from my own page on Python insights :-)
Upvotes: 9
Reputation: 7411
>>> from UserString import MutableString
>>> s = MutableString('abcd')
>>> s[2] = 'e'
>>> print s
abed
Upvotes: 0
Reputation: 342333
mystring=list("abcdef")
mystring[4]="Z"
print ''.join(mystring)
Upvotes: 3