Replacing one character of a string in python

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.


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.

Tags:

Python