Line indexing in Python

Lie Ryan lie.1296 at gmail.com
Fri Dec 18 13:18:11 EST 2009


On 12/19/2009 4:33 AM, seafoid wrote:
>
> Thanks for that Lie.
>
> I had to have a think about what you meant when you referred to control
> going to a.write(line).

and if-elif-elif-... chain is executed sequentially and when a match is 
found, the rest of the chain is skipped. Your code:

if line.startswith("0"):
     # BLOCK 1 #
elif line.endswith("0"):
     # BLOCK 2 #
elif line.startswith("0"):
     # BLOCK 3 #

BLOCK 3 never gets executed, since if line.startswith("0") is true, your 
BLOCK 1 is executed and the rest of the if-elif chain is skipped.


> Have you any suggestions how I may render this code undead or should I scrap
> it and create something new?

I still don't get what you want to do with the code, but to make it not 
dead you can either:

for line in blah:
     if line.startswith("0"):
         a.write(line)
         lists_b = line.strip().split()
         print lists_b
     elif line.endswith("0"):
         lists_a = line.strip().split()
         print lists_a

or this:

for line in blah:
     if line.startswith("0"):
         a.write(line)
     if line.endswith("0"):
         lists_a = line.strip().split()
         print lists_a
     elif line.startswith("0"):
         lists_b = line.strip().split()
         print lists_b

depending on which one seems more readable to you.

> My confusion and ineptitude is perhaps explained by my being a biologist :-(
>
> Thanks,
> Seafoid.




More information about the Python-list mailing list