Modify one character in a string

Paul Rubin http
Thu May 25 07:40:11 CEST 2006


"mp" <mailpitches at email.com> writes:
> How do I go about modifying one character in a string elegantly?
> In other words, I want a function that will change 'aaaa' to 'aaza',
> given the index 2 of the character in the string.

Ehh, there are various ways, all ugly.
   x = 'aaaa'
   y = x[:2] + 'z' + x[3:]
is the most direct.

> Also, how do I do this when dealing with a file ; which file mode
> should I use and what function should I use to modify a single
> character once in that file mode?

You mean you want to change a character in a file?

   f = open(file, 'r+')   # open for reading and writing
   f.seek(2)              # position at character index 2
   f.write('z')           # put a 'z' there
   f.seek(0)              # rewind
   print f.read()         # get entire contents and see the change

You could also look at the mmap module.



More information about the Python-list mailing list