like a "for loop" for a string

mblume mblume at socha.net
Sun Aug 17 16:47:20 EDT 2008


Am Sun, 17 Aug 2008 13:12:36 -0700 schrieb Alexnb:
> Uhm, "string" and "non-string" are just that, words within the string.
> Here shall I dumb it down for you?
> 
Please, bear with us. You are deep into the problem, we are not.
It doesn't help to be rude. If you can explain your problem well, you are
halfway through to the solution.

> 
> string = "yes text1 yes text2 yes text3 no text4 yes text5+more Text yes
> text6  no text7 yes text8"
> 
> It doesn't matter what is in the string, I want to be able to know
> exactly how many "yes"'s there are.
> I also want to know what is after each, regardless of length. So, I want
> to be able to get "text1", but not "text4" because it is after "no" and
> I want all of "text5+more Text" because it is after "yes". It is like
> the yeses are bullet points and I want all the info after them. However,
> all in one string.
> 

How about this:
>>> s="yes t1 yes t2 no t3 yes t4 no t5"
>>> l=s.split()
>>> l
['yes', 't1', 'yes', 't2', 'no', 't3', 'yes', 't4', 'no', 't5']
>>> for i in range(1,len(l),2):
...     if l[i-1] == 'yes': print l[i]
t1
t2
t4
>>> 

Now your problem is reduced to splitting the input into (yes/no) and 
(text) pairs. For a simple string like the one above split() is ok, but
> string = "yes text4 yes text5+more Text yes text6  no text7"
will be split into [ ... 'yes', 'text5+more', 'Text', 'yes', ...], 
breaking my simple algorithm. 

You could look for the index() of 'yes' / 'no', but then you'd have to 
make sure that 'text' does not contain 'yes' or 'no'.

HTH.
Martin




More information about the Python-list mailing list