replace value of a specific position

John Hunter jdhunter at ace.bsd.uchicago.edu
Thu Jul 10 13:50:37 EDT 2003


>>>>> "Tom" == Tom  <llafba at gmx.net> writes:

    Tom> Hi, I want to replace a specific part of a string. I tried
    Tom> replace but this doesn't work the way I want it, because it
    Tom> checks and replaces all values and not the position (index).

    Tom> t = '010010101001001110100101010111' t = t.replace(t[5], '2')

strings are immutable and cannot be changed.  You can represent a
string as a list, change the list, and then convert back to a string.
If you need to make lots of changes, keep it as a list until you are
done and need the string back

t = '010010101001001110100101010111'
l = list(t)
l[5] = '2'
print l

# now convert back to string
tnew = ''.join(l)
print tnew

JDH





More information about the Python-list mailing list