Find a substring withing a string...

drs drs at ecp.cc
Sat Jun 21 02:32:33 EDT 2003


"FooBar" <abc at attbi.com> wrote in message
news:MPG.195db98e90b83bb49899fe at netnews.attbi.com...
> OK I will be the first to admit that I am VERY new to Pythin and
> know little of the syntax of this language.  I want to perform the
> simple task of testing to see if a substring exists within string.  I
> think the syntax is find(sting,substring) and the return is -1 if the
> substirng is not found otherwise the start position of the substring in
> the string.  is this correct?
>
> Moreover is this code totally screwed?
>
>
> takeaction = find(stringvar,'LITERALSUB')
> if takeaction != -1:
>     action_to_take_if_found
> else:
>     action_tp_take_if_not_found

find() is not builtin, so you would need to do something like

>>> import string
>>> string.find(stringvar,'LITERALSUB')

but this is the old way of doing things.  since 2.0 (?) one can do it this
way

>>> if stringvar.find('LITERALSUB') >= 0:
>>>     action_to_take_if_found
>>> else:
>>>     action_tp_take_if_not_found

as the string is an object with a find method. more importantly, however, is
that you should test code snippets like this at the command prompt.  it's
the best way to learn.

-drs






More information about the Python-list mailing list