string manipulation question

Chris Liechti cliechti at gmx.net
Sat Nov 10 13:26:22 EST 2001


[posted and mailed]

"AT&T News" <wavy_gravy at worldnet.att.net> wrote in
news:iUcH7.106616$WW.6280952 at bgtnsc05-news.ops.worldnet.att.net: 

> 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.
> 
> TIA
> 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')
'MAMAL'
>>> ident('a cat sits on the veranda')
'FELINE'
>>> print ident('no animal here')
None


-- 
Chris <cliechti at gmx.net>




More information about the Python-list mailing list