string manipulation question

Oliver Fromme olli at
Mon Nov 12 15:59:36 CET 2001

AT&T News <wavy_gravy at> wrote:
 > I have a string (line) that might contain, for example *any* *one* of the
 > patterns or words "whale" , "cat".
 > How do I elegantly set a variable say "animal" depending upon what word is
 > there. I.e I want
 > animal = "MAMMAL" if line contains the word "whale"
 > or
 > animal = "FELINE" if line contains the word "cat".
 > is there a elegant way to code the above construct, I have 10 of these
 > patterns/keywords that can be found in a line. I thought of using a
 > dictionary for the keyword patterns, but the pattern/keyword does not have
 > any known context in the line.

Don't know if this is what you want, but it seems to match
your description, and I think it's fairly "elegant" ...

>>> words = {"whale": "MAMMAL", "cat": "FELINE"}
>>> def find_animal(line):
...     return filter(lambda (key, val): key in line.split(), words.items())[0][1]
>>> find_animal("My cat has white feet.")
>>> find_animal("There's a whale in my bath tube.")

You'll probably want to split that long line somehow, and
also catch IndexError exceptions (which are raised if none
of the words occur in the line).


Oliver Fromme, secnetix GmbH & Co KG, Oettingenstr. 2, 80538 München
Any opinions expressed in this message may be personal to the author
and may not necessarily reflect the opinions of secnetix in any way.

"All that we see or seem is just a dream within a dream" (E. A. Poe)

More information about the Python-list mailing list