[Tutor] script error question [checking for substrings]

Magnus Lycka magnus@thinkware.se
Tue Dec 17 08:17:01 2002


At 12:15 2002-12-17 +0000, alan.gauld@bt.com wrote:
>For that, and any other general search, find() is undoubtedly best.

Another convenient solution if you don't need to know location is re.findall().

 >>> import re
 >>> text = "I am a long string and I continue for quite a while, blah blah 
blah..."
 >>> subString = "on"
 >>> re.findall(subString, text)
['on', 'on']

Then you also get wildcard abilities.

 >>> subString = r"\b\w\w\w\b" # Look for three letter words.
 >>> re.findall(subString, text)
['and', 'for']

 >>> subString = r"\ba.*?\b" # Words that start with 'a'
 >>> re.findall(subString, text)
['am', 'a', 'and', 'a']




-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se