Changing the middle of strings in a list--I know there is a better way.
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()
> #Loop through the file and format each line
> while a > 0:
> # write the changed data (list) to a file
> FileOut = open("C:\\path\\to\\file", "w")
> 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")
To modify a file inplace have a look at the fileinput module.
More information about the Python-list