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

Ben bmilliron at gmail.com
Tue Oct 21 19:28:49 CEST 2008


Hello All:

I am new to Python, and I love it!! I am running 2.6 on Windows. I
have a flat text file here is an example of 3 lines with numbers
changed for security:

999999999088869199999999990200810999999
999999999088869199999999990200810999999
999999999088869199999999990200810999999


I want to be able to replace specific slices with other values. My
code below reads a file into a list of strings. Since strings are
immutable I can't assign different values to a specific slice of the
string. How can I accomplish this? I read some posts on string
formatting but I am having trouble seeing how I can use those features
of the language to solve this problem.

The code below just puts an 'R' at the beginning of each line like
this:

R999999999088869199999999990200810999999
R999999999088869199999999990200810999999
R999999999088869199999999990200810999999


But what I want to do is change the middle of the string. Like this:

R999999999088869CHANGED99990200810999999
R999999999088869CHANGED99990200810999999
R999999999088869CHANGED99990200810999999

#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,

-Ben



More information about the Python-list mailing list