In python, are strings mutable? The line someString[3] = \"a\"
throws the error
TypeError: \'str\' object does not support item assig
>>> import ctypes
>>> s = "1234567890"
>>> mutable = ctypes.create_string_buffer(s)
>>> mutable[3] = "a"
>>> print mutable.value
123a567890
Just define a new string equaling to what you want to do with your current string.
a = str.replace(str[n],"")
return a
Python strings are immutable, which means that they do not support item or slice assignment. You'll have to build a new string using i.e. someString[:3] + 'a' + someString[4:]
or some other suitable approach.
Instead of storing your value as a string, you could use a list of characters:
>>> l = list('foobar')
>>> l[3] = 'f'
>>> l[5] = 'n'
Then if you want to convert it back to a string to display it, use this:
>>> ''.join(l)
'foofan'
If you are changing a lot of characters one at a time, this method will be considerably faster than building a new string each time you change a character.
In new enough pythons you can also use the builtin bytearray
type, which is mutable. See the stdlib documentation. But "new enough" here means 2.6 or up, so that's not necessarily an option.
In older pythons you have to create a fresh str
as mentioned above, since those are immutable. That's usually the most readable approach, but sometimes using a different kind of mutable sequence (like a list of characters, or possibly an array.array
) makes sense. array.array
is a bit clunky though, and usually avoided.