looping through a list
Steve Holden
sholden at holdenweb.com
Sat Apr 27 08:16:34 EDT 2002
"Hugh" <h.e.w.frater at cs.cf.ac.uk> wrote in message
news:e2e9e807.0204261611.7514b387 at posting.google.com...
> I need help with a really simple algorithm that I can't get my head
> around. I am looping through the list returned by a dcoracle2 execute
> statement and need to add each item of data surrounded by some HTML
> table tags to a string called text which I then pass to a page
> generation method. At the moment I've got this:
>
> result = c.fetchone()
Remember that the result will be a tuple. It will, therefore, never be equal
to "". When empty it will be equal to ().
> if (result != ""):
> i=0
> text = '<tr width = "80%" align = "center">'
> while (i != len(result)+1):
> i = i + 1
> text = text + '<td align = "center" valign =
> "top">'+str(result[int(i)]) +'</td>'
> text = text + "</tr>"
> page.generate("","",sessionID,text)
> else:
> text = '<h4>No items found</h4>'
> page.generate("","",sessionID,text)
>
If would seem simpler to do the following:
if result:
text = '''
<tr width="80%%" align="center">
%s
</tr>''' % "\n ".join(['<td align="center" valig="top">%s</td>' % c
for c in result])
>
> At the moment, it keeps saying list index out of bounds and I don't
> know where I'm going wrong. I've tried all sorts of things in the
> While statement and still can't get it going.
>
Not using a while statement will cure all those blues :-)
regards
Steve
--
home: http://www.holdenweb.com/
Python Web Programming:
http://pydish.holdenweb.com/pwp/
More information about the Python-list
mailing list