Modify one character in a string
Roy Smith
roy at panix.com
Thu May 25 10:04:42 EDT 2006
"mp" <mailpitches at email.com> 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.
Strings are immutable, so you can't change a string. The best you can do
is create a new string from the old one. Something like:
>>> old = 'aaaa'
>>> new = old[:2] + 'z' + old[3:]
>>> print new
aaza
or a few variations on that theme.
> 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?
This is a much more complicated question, because it depends on the details
of the operating system you're using. On Unix, you can seek to a specific
place in a file, write a single character, seek to EOF, and you've done an
in-place single character edit of the file. I don't know if that works on
other OS's or not.
More information about the Python-list
mailing list