Changing the middle of strings in a list--I know there is a better way.

Terry Reedy tjreedy at udel.edu
Tue Oct 21 22:31:59 CEST 2008


Duncan Booth wrote:
> Ben <bmilliron at gmail.com> wrote:
> 
>> Since strings are
>> immutable I can't assign different values to a specific slice of the
>> string. How can I accomplish this? 

> You probably don't want to use readlines. It is almost always cleaner just 
> to iterate over the file itself.
> 
> You can't change an existing string, but creating a new string isn't 
> exactly rocket science.
> 
> lines = []
> for line in F:
>     modified = line[:16] + "CHANGED" + line[23:]
>     # or maybe
>     modified = line.replace("1999999", "CHANGED")
>     lines.append(modified)
> FileOut.writelines(lines)

If you want your program to scale to indefinitely large files, and you 
edit each line independently, without using date from other lines, read 
a line *and* write the new line immediately

for line in F:
   FileOut.write(<modified>)

Where <modified> is one of the suggested expressions, or a temporary 
variable calculated on multiple lines.

To edit a line 'in-place', one can use the array module for mutable 
array of bytes (or the 3.0 bytearray), but I would only both with 
extensive editing.




More information about the Python-list mailing list