Drone Pirate Drone Pirate - 14 days ago 6
Python Question

text-changing function does not execute

I have tried to change some values on an script.txt using a python program.

So, the following function makes that work:

def textx(x,y):
with open("script.txt","r") as f:
newline = []
for word in f.readlines():
newline.append(word.replace(x, y))
with open("script.txt","w") as f:
for line in newline:
f.writelines(line)
return


Where
x
and
y
must quoted numbers, i.e., for example
"2"
and
"3"
.
Since I need to make a loop over many values of
x
and
y
, I created a list of quoted numbers as follows:

def quotes(x):
Q = '"%s"'%x
return Q;

SS = list();
QS = list();

for i in range(4):
SS.append(i)

for j in SS:
i = quotes(j)
QS.append(i)


But when I try to run the function
textx()
as follows:

textx(QS[0], QS[3])


The program runs without any error, but I expect in the
script.txt
file that the
0
-value will be changed to
3
, but this does not happen. So, how I can make the
text
x function run properly with the elements of the
QS
list?

Answer

The problem is probably because the strings you put into the QS list include the two doubles quote characters ", so the call to the string replace() method fails and doesn't do anything.

If you change the quotes() function to:

def quotes(x):
    Q = '%s' % x
    return Q

It should then work. It also means you don't really need to have separate SS and QS lists because you could just create the one list needed to drive the textx() function with this one-liner (assuming the new list is named new_list):

new_list = [str(i) for i in range(4)]

And then use it instead of QS to call textx().
In other words:

textx(new_list[0], new_list[3])
Comments