like a "for loop" for a string

Fredrik Lundh fredrik at pythonware.com
Sun Aug 17 16:38:40 EDT 2008


Alexnb wrote:

> Uhm, "string" and "non-string" are just that, words within the string.

>From what I can tell, this is the first time you use the word "word" in 
your posts.

 > Here shall I dumb it down for you?

No, you should do what you should have done from the very beginning: 
explain what you want in unambiguous terms.  Given that the "dumbed 
down" version only has superficial similarities with your earlier posts, 
this is obviously something that you need to practice.

> 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"

It's after "yes" as well, as part of the string "text3 no text4".

 > 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.

Ok, so you have *two* separators, "yes" and "no", and you want all the 
text fragments that follow a yes separator?  Do you seriously argue that 
anyone anywhere would have been able to figure that out from your 
original description?

 > funString = "string string string non-string non-string string"
 > and
 > for "string" in funString:
 >      print something

Anyway, I guess I'd split on the separator, and use a list comprehension 
to pick out the texts you want.  E.g.

 >>> text = "... as above ..."
 >>> parts = re.split(r"\b(yes|no)\b", text)
 >>> parts = [parts[i+1].strip()
...         for i in xrange(1, len(parts), 2)
...         if parts[i] == "yes"]
 >>> len(parts)
6
 >>> parts
['text1', 'text2', 'text3', 'text5+more Text', 'text6', 'text8']

Alternatively, just use text.split() to split the text in a list of 
words, and loop over that, keeping track of the words you want to keep. 
A bit more work, but maybe easier to grok if you're not used to list 
comprehensions/generator expressions.

</F>




More information about the Python-list mailing list