replace value of a specific position

Peter Hansen peter at engcorp.com
Thu Jul 10 14:21:04 EDT 2003


Tom wrote:
> 
> 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

Try this instead:

>>> t = '010010101001001110100101010111'
>>> import array
>>> x = array.array('c', t)
>>> x
array('c', '010010101001001110100101010111')
>>> x[5] = '2'
>>> x.tostring()
'010012101001001110100101010111'

-Peter




More information about the Python-list mailing list