Pattern matching with string and list

Brett g Porter bgporter at acm.org
Tue Dec 13 17:40:45 EST 2005


BartlebyScrivener wrote:
> Even without the marker, can't you do:
> 
> sentence = "the fabric is red"
> colors = ["red", "white", "blue"]
> 
> for color in colors:
>     if (sentence.find(color) > 0):
>         print color, sentence.find(color)
> 
That depends on whether you're only looking for whole words:

 >>> colors = ['red', 'green', 'blue']
 >>> def findIt(sentence):
...    for color in colors:
...       if sentence.find(color) > 0:
...          print color, sentence.find(color)
...
 >>> findIt("This is red")
red 8
 >>> findIt("Fredrik Lundh")
red 1
 >>>

It's easy to see all the cases that this approach will fail for...



More information about the Python-list mailing list