Modify one character in a string

Larry Bates larry.bates at websafe.com
Thu May 25 19:05:09 CEST 2006


mp wrote:
> X-No-Archive
> 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.
> 
> 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?
> 
> Thanks
> MP
> 
IMHO the most elegant method is something like:

def switchchar(srcstring, position, character):
    b=list(srcstring)
    b[2]=character
    return ''.join(b)

You should open file in binary 'b' mode.  Use .seek() method
to seek to the character you want to replace.  use .write() method
to write one character.

-Larry



More information about the Python-list mailing list