for loop troubles
Greg Jorgensen
gregj at pobox.com
Mon Apr 30 01:57:48 EDT 2001
In article <3AE8EFCC.CEFCF61F at nmt.edu>, "Jeff Shipman" <shippy at nmt.edu>
wrote:
> I've used this method before to do funky for loop stuff, but for some
> reason, I'm getting a line skipped this time.
>
> What I'm trying to do is convert items that have one or more tabs at the
> beginning of a line followed by a * into unordered list HTML. If I ever
> hit more tabs than I'm currently at, I must be in a sublist so I call
> this function recursively. It all works great except when I come out of
...snip...
Simplify. Try this:
def printlist(lines):
"print lines starting with <tab>* as HTML nested unordered lists"
depth = 0
indent = " " # spaces to indent HTML
for line in lines:
# does line begin with one or more tabs followed by *?
i = line.find("*")
if i >= 0 and line[0:i] == ("\t" * i):
if i > depth: # increase indent
print (indent * depth) + "<UL>"
depth += 1
elif i < depth: # decrease indent
depth -= 1
print (indent * depth) + "</UL>"
print (indent * depth) + "<LI>" + line[i+1:]
else:
# no leading tabs, output line as-is
print (indent * depth) + line
# close all lists
while depth > 0:
depth -= 1
print (indent * depth) + "</UL>"
Greg Jorgensen
PDXperts LLC
gregj at pobox.com
More information about the Python-list
mailing list