replace value of a specific position

Joe Francia usenet at soraia.com
Thu Jul 10 19:47:41 CEST 2003


Tom wrote:
> Hi,
> 
> I want to replace a specific part of a string. I tried replace but this 
> doesn't work the way I want it, because it checks and replaces all 
> values and not the position (index).
> 
> t = '010010101001001110100101010111'
> t = t.replace(t[5], '2')
> 
> This is just a bad example of what I tried. It produces this output:
> 
> 212212121221221112122121212111
> 
> But I wanted:
> 
> 010012101001001110100101010111
> 
> I couldn't find anything in the python library. I probably looked at the 
> wrong place! :-) That's why I would appreciate your help.
> 
> Thank you very much, Tom
> 

Strings are immutable in Python.  Try something like:

 >>> t = '010010101001001110100101010111'
 >>> t = string.join([t[:5], '2', t[6:]], '')
 >>> t
010012101001001110100101010111

jf





More information about the Python-list mailing list