Replace single character at given position

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Tue Sep 19 17:51:30 EDT 2006


Martin Kulas:
> Are there better (faster) ways to achieve my goal?
> I have looked through the methods of type ``string''
> but I have not found any appropriate method or function.

Python strings are immutable, so you can't modify them, so you can't
find methods to change them. I agree that sometimes this is a pain,
expecially if you come from languages where strings are mutable.

The best solution may seem the strangest, that is "to not need to do
that". Often with python you can use different (higher level) code that
doesn't require to change many single chars inside a string.

A second way is to use a list of strings with len=1. Like this:
>>> idx = 1
>>> s1 = "pxthon"
>>> l1 = list(s1)
>>> l1[idx] = 'y'
... more processing on the elements of l1, then at the end:
>>> "".join(l1)
'python'

Note that structures like that l1 require a lot of memory.


A third solution is to use an array of chars:
>>> from array import array
>>> a1 = array("c", s1)
>>> a1
array('c', 'pxthon')
>>> a1[idx] = "y"
>>> a1
array('c', 'python')
>>> a1.tostring()
'python'

Bye,
bearophile




More information about the Python-list mailing list