string manipulation question

Chris Liechti cliechti at
Sat Nov 10 19:26:22 CET 2001

[posted and mailed]

"AT&T News" <wavy_gravy at> wrote in
news:iUcH7.106616$WW.6280952 at 

> Greetings,
>  I am looking for a more resaonable way to do the following, instead of
>  ugly 
> "if", "elif" constructs. Here goes:
> 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.
> MO

don't know if i get what you want, but here's my solution..

>>> animals = {'whale':'MAMAL', 'cat':'FELINE'}
>>> def ident(s):
... 	for word in s.split():
... 		for ani, group in animals.items():
... 			if word == ani:
... 				return group
>>> ident('there is more than one whale out there in the sea')
>>> ident('a cat sits on the veranda')
>>> print ident('no animal here')

Chris <cliechti at>

More information about the Python-list mailing list