[Tutor] How to skip to next line in for loop

bob gailer bgailer at gmail.com
Fri May 2 16:18:16 CEST 2008


Brain Stormer wrote:
> Well,
> I was somewhat confused with all of the answers so I decided to go 
> with  my/following method.  Kent's method has 4 fewer lines of code 
> than mine and cleaner.  Please correct me if I am fundamentally wrong.
>
> f=open('file.txt',r)
>
> for line in f.read().split():
>     if line == "3"
>           position = True
>     else:
>           position = False
>     if position == True
>           print line
>           position = False
> f.close()
>
Yikes! That won't compile (missing : at end of if statements). After 
correcting, will print 3.

How about this if you want less lines of code:

f = open('file.txt',r).readlines()
print f[[x+1 for x,line in enumerate(f) if line.rstrip() == "3"][0]]

-- 
Bob Gailer
919-636-4239 Chapel Hill, NC



More information about the Tutor mailing list