Reputation:
When I execute the following code :
file1 = open("sources.conf", "r");
datalist = list(file1.readlines());
datalist[3][32]= "11";
I get this error: 'str' object does not support item assignment
. After reading a bit, I discovered that it is not possible to change the string in python. Is there any other work around for this?
Upvotes: 1
Views: 163
Reputation: 27812
How about this (using slices):
datalist[3] = datalist[3][:31] + "11" + datalist[3][33:]
Also, Python doesn't use ;
after each statement.
You can also change your string to a list, and back again:
temp = list(datalist[3])
temp[32:34] = "11"
datalist[3] = "".join(temp)
Upvotes: 0
Reputation: 4182
I would advise You to read line by line and modify string If needed (I am not sure that readlines()
is the best solution (as It reads whole file into memory)
with open("sources.conf", "r") as file1
datalist = []
for i, line in enumerate(file1):
if i == 3:
datalist[i] = line[:32] + "11" + line[33:]
else:
datalist[i] = line
or use join
methods
datalist[i] = ''.join([line[:32], "11", line[33:]])
Upvotes: 0
Reputation: 1125018
Slice the string and reassign it to the same position in your list:
datalist[3] = datalist[3][:31] + '11' + datalist[3][33:]
Upvotes: 2