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

Duncan Booth duncan.booth at invalid.invalid
Tue Oct 21 19:45:25 CEST 2008


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? 
> 
...
> #My Current Code
> 
> # read the data file in as a list
> F = open('C:\\path\\to\file', "r")
> List = F.readlines()
> F.close()
> 
> #Loop through the file and format each line
> a=len(List)
> while a > 0:
> 
>     List.insert(a,"2")
>     a=a-1
> 
> # write the changed data (list) to a file
> FileOut = open("C:\\path\\to\\file", "w")
> FileOut.writelines(List)
> FileOut.close()
> 
> Thanks for any help and thanks for helping us newbies,
> 

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)


To modify a file inplace have a look at the fileinput module.



More information about the Python-list mailing list