[Tutor] script error question [checking for substrings]

alan.gauld@bt.com alan.gauld@bt.com
Mon Dec 16 12:38:30 2002


> >>> '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
>>>

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld