[Tutor] process and modify a list of strings, in place

Dave Angel davea at ieee.org
Thu Feb 10 23:52:44 CET 2011


On 01/-10/-28163 02:59 PM, John Martinetti wrote:
> Hello -
>
Welcome,

>
> <snip>
>     # - create a record from all the fields
>     linedata = (vendornum, vendorname, ordernum, ordersuffix, orderdate,
> buyer, partnum, qty, comment)
>     # - append the record to the list of records representing the CQ report
>     openPOs.append(linedata)
>
(snip)
>
> The part I'm having a problem with is once I've detected that a record has a
> blank buyerID field, I can't seem to figure out how to change it, in place.
> I've tried finding the index of the openPOs using this:
> openPOs.index(line)
> and then trying to change the item like this:
> openPOs[openPOs.index(line),5] = "NOBUYER"
> but I'm getting a strange error:  "TypeError: 'tuple' object does not
> support item assignment"
>
>

You assign a tuple to linedata with the (vendornum, vendorname, ...) 
syntax.  Change those to square brackets and it'll be a list, which is 
modifiable.

There are other ways to simplify your code, but the most relevant might 
be to modify line[5] directly:
    if line[5] == "      " :
        print "The field is blank!!!"
        line[5] = "NOBUYER"

So first change it so that individual "line"s are lists instead of 
tuples. Then change the list item directly, without resorting to 
searching with index().

Another thing I note:  You're counting on the file ending with a blank 
line.  If you're sure that'll always be the case, fine.  But if you 
really just want to read the whole file, replace the while True loop 
with something like:

for record in txtreport:

and if you need to ignore blank lines, use
     if record="" : continue

-- 
--
davea at ieee.org


More information about the Tutor mailing list