1

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?

3
  • file1.readlines() or list(file1) is enough.. Commented Jul 3, 2013 at 16:56
  • 1
    Could you elaborate on what you are trying to do by assigning "11" to datalist[3][32]? Commented Jul 3, 2013 at 17:22
  • on datalist[3][32] there is a port number hard codded into the code, I am trying to write a script that will take user input and modify the COMPORT number in the configuration file. I know for simple things like this I can do it manually by opening the config file, but I wanted to learn python so wanted to do it via a script. Commented Jul 4, 2013 at 7:20

3 Answers 3

2

Slice the string and reassign it to the same position in your list:

datalist[3] = datalist[3][:31] + '11' + datalist[3][33:]
Sign up to request clarification or add additional context in comments.

Comments

0

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:]])

Comments

0

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)

1 Comment

temp[32:34] = "11" is better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.