finding an element in a string

Will Maier willmaier at ml1.net
Mon Jun 25 17:14:18 EDT 2007


On Mon, Jun 25, 2007 at 04:09:50PM -0400, Miguel Oliveira wrote:
> I want to make an if statement in which I would like to find a
> certain word in a sentence; here is what i have so far:
> 
>    x = raw_input("how are you?")
> 
>    if x == "fine":
>              print "Good."
> 
> But that, obviously, will only respond "good" when one writes
> "fine". I was looking for a way for the program to respond "good"
> to any sentence that would contain the word "fine" in it.

Since strings are sequences, too, you can use the membership
operator ('in'):

    >>> input = "spam; spam, eggs and spam; spam, sausage and spam..."
    >>> if "spam" in input:
    >>>    sing()

http://docs.python.org/ref/sequence-types.html

-- 

[Will Maier]-----------------[willmaier at ml1.net|http://www.lfod.us/]



More information about the Python-list mailing list