[Tutor] script error question [checking for substrings]

Don Arnold Don Arnold" <darnold02@sprynet.com
Mon Dec 16 19:14:01 2002


----- Original Message -----
From: <alan.gauld@bt.com>
To: <dyoo@hkn.eecs.berkeley.edu>; <idiot1@netzero.net>
Cc: <tutor@python.org>
Sent: Monday, December 16, 2002 11:37 AM
Subject: RE: [Tutor] script error question [checking for substrings]


> > >>> 'hello' in 'hello world'
> > Traceback (most recent call last):
> >   File "<stdin>", line 1, in ?
> > TypeError: 'in <string>' requires character as left operand
> > ###
> >
> > Instead of 'in', you'll probably want to use the 'find()'
> > method, which tells us exactly the position where the
> > smaller string starts to occurs.
>
> An alternative is to split the string:
>
> >>> "hello" in "hello world".split()
> 1
> >>>
>
> which is, I think, easier to read than the equivalent
> (and possibly faster!) find() version:
>
> >>> print "hello world".find("hello") != -1)
> 1

But your split() alternative fails miserably if the substring you're looking
for contains spaces:

>>> "hello world".find("o w")
4
>>> "o w" in "hello world".split()
0

Just something to beware of.

Don