How to find if a string contains another string

sandipm sandip.more at gmail.com
Tue Oct 30 00:50:27 EDT 2007


you can use "find" function...which gives index of occurrence of
smaller one in bigger one
and return -1 if does not exists..


if bigstring.find(smallone) > -1:
    return true
else:
    return false


sandip




On Oct 30, 9:15 am, "Borse, Ganesh" <ganesh.bo... at credit-suisse.com>
wrote:
> Sorry, am getting this error.
>
> >>> bigstring="python anaconda boa cobra"
> >>> smallone="boa"
> >>> smallone in bigstring
>
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: 'in <string>' requires character as left operand
>
> >>> if smallone in bigstring:
>
> ...    print 'ok'
> ... else:
> ...     print 'nok'
> ...
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: 'in <string>' requires character as left operand
>
> Do I need to import any module?
>
> Thanks,
> Ganesh
>
> -----Original Message-----
> From: Gary Herron [mailto:gher... at islandtraining.com]
> Sent: 30 October 2007 12:09
> To: Borse, Ganesh
> Cc: python-l... at python.org
> Subject: Re: How to find if a string contains another string
>
> Borse, Ganesh wrote:
> > Hi,
>
> > Am new to python.
> > May someone please help me know this?
>
> > How can we check whether one big string contains another small string?
>
> > E.g.
> > bigstring="python anaconda boa cobra"
> > smallone="boa"
>
> Use the operator named in:
>
> >>> bigstring="python anaconda boa cobra"
> >>> smallone="boa"
> >>> smallone in bigstring
> True
>
> Often used in if statements like this:
>
> >>> if smallone in bigstring:
> ...   print 'contained'
> ... else:
> ...   print 'not'
> ...
> contained
>
> Gary Herron
>
> > If 0 == contains(bigstring,smallone):
> >         print "Yes, boa is snake.."
>
> > Is there any function like "contains" or "exists" in python?
> > What are different alternatives we have?
>
> > Please help.
>
> > Thanks and Regards,
> > Ganesh
>
> > ======================================================================
> > ======== Please access the attached hyperlink for an important
> > electronic communications disclaimer:
>
> >http://www.credit-suisse.com/legal/en/disclaimer_email_ib.html
> > ======================================================================
> > ========
>
> ===========================================================================­===
> Please access the attached hyperlink for an important electronic communications disclaimer:
>
> http://www.credit-suisse.com/legal/en/disclaimer_email_ib.html
> ===========================================================================­===





More information about the Python-list mailing list