String processing inside lists
Hans Nowak
hnowak at cuci.nl
Mon Feb 28 17:28:59 EST 2000
On 28 Feb 00, at 21:58, Gary Moore wrote:
> After diligently and successfully going through 'Programming Python' I
> decided that a good first project would be to take my DVD collection (228
> Discs) and build three different files (a tab delimited file for import
> into a database, an xml file for each movie, and a text file for each
> movie). I decided to gather the information from the Internet movie
> database .list files and then process and sort the output in python.
>
> The problem happened when I tried to use the construct:
>
> for x in actors
>
> to process the list of actors prior to output.
>
> When I use the string library to process this list, I want the actual
> strings contained in the list to change. What I found was that no matter
> how I tried to change the strings in the actors list, I was unsuccessful.
> e.g.
>
> temp = replace(x,'\012','')
> x = temp
>
> When I print x, I get the line with the text replaced. However, when I
> view the line in the original array actors, the changes were not made.
True; this construct loops over the actors list, feeding each element to x.
However, x is, shall we say, "stand-alone"; it has no direct relation with
the original list. Thus,
for x in actors:
x = 'blah'
will *not* change all elements of the list to 'blah'.
> The only way I could overcome this problem was to change the for statement
> to:
>
> for x in range(len(actors))
>
> and then subscript the actors list to obtain the results e.g.
>
> temp = replace(actors[x],'\012','')
> actors[x] = temp
This construct changes the elements of the list. You loop over an index,
like you would in, for instance, C.
> My concern is that I must not be understanding some basic concept
> concerning the FOR loop in Python. I reread the material in 'Learning
> Python', but still could not understand why the first solution above did
> not work.
The x in 'for x in actors' can be seen as a "read-only" value. You can
change it, but it won't affect the list, as you have found out.
> I fnally completed a working prototype and successfully carried out the
> conversion of all of the information. It was amazingly fast, and I was
> very impressed with the power available with a minimum of effort (1 day).
>
> If anyone could clarify the situation above, I would appreciate it.
HTH,
--Hans Nowak (zephyrfalcon at hvision.nl)
Homepage: http://fly.to/zephyrfalcon
You call me a masterless man. You are wrong. I am my own master.
More information about the Python-list
mailing list