like a "for loop" for a string

Grzegorz Staniak gstaniak at wp.pl
Sun Aug 17 16:31:07 EDT 2008


On 2008-08-17, Alexnb <alexnbryan at gmail.com> wroted:

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

----- cut here -----
>>> import re
>>> foo = "yes text1 yes text2 yes text3 no text4 yes text5+more Text yes
>>> text6 no text7 yes text8"
>>> results = re.findall("yes", foo)
>>> len(results)
6
>>> results
['yes', 'yes', 'yes', 'yes', 'yes', 'yes']
----- cut here -----

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

I guess this can be done with regular expressions:

http://www.python.org/doc/current/lib/module-re.html

Read about groups, then write an appropriate regex.

GS
-- 
Grzegorz Staniak <gstaniak _at_ wp [dot] pl>



More information about the Python-list mailing list