[Tutor] how to extract data only after a certain condition is met

Knacktus knacktus at googlemail.com
Wed Oct 6 19:32:56 CEST 2010

Am 06.10.2010 18:25, schrieb Eduardo Vieira:
> The other day I was writing a script to extract data from a file from
> the line where a text is found to the end of the file. The same
> functionality is this sed script:
> '1,/regexp/'d
> I couldn't put my head to work around this and came up with a solution
> using list slicing. But how can I do that? I was experimenting with a
> simple list and I came up with this. I wonder if I shouldn't you a
> "while" statement, but how?
> a = ['m', 'a', 'r', 'i', 'g', 'o', 'l', 'd']
> b = True
> for letter in a:
> 	if letter != 'i' and b:
> 		continue
> 	elif letter == 'i':
> 		b = False
> 	else:
> 		print letter
> Ok. This works, but I wonder if I shouldn't you a "while" statement, but how?
Why would you want to use a while-loop? You would need to somehow stop 
the iteration (by catching some EOF Exception or the like). I think it's 
fine to use a for-loop as you have a predefined fixed number of 
iterations. I think your approach is OK. Easy to understand. But what if 
there's a second "i" after the first? In your solution all "i" are 
skipped. Also, I would choose clearer names:

letters = ['m', 'a', 'r', 'i', 'g', 'o', 'l', 'd', 'i', 'n', 'i', 'o']
skip_letter = True

for letter in letters:
     if letter == 'i' and skip_letter:
	skip_letter = False
	continue  # if you don't want the first occurrence of "i"
     if not skip_letter:
  	print letter



More information about the Tutor mailing list