"str.contains(part)" or alternatives?

Stefan Schwarzer sschwarzer at sschwarzer.net
Thu Sep 12 22:01:32 CEST 2002

Hi Skip

Skip Montanaro wrote:
>     >>> try:
>     ...     s.index('ll')
>     ...     do_something_if_found()
>     ... except ValueError:
>     ...     do_something_if_not_found()
>     Stefan> This has the problem that a ValueError raised in
>     Stefan> do_something_if_found() may give the false impression that the
>     Stefan> substring isn't contained in the string s. 
> I try to minimize the amount of code executed in try blocks.

Me too. That above was only a (bad) example. ;-)

 > Use this instead:
>     try:
>         s.index('ll')
>     except ValueError:
>         do_something_if_not_found()
>     else:
>         do_something_if_found()

I just read today in the Python Cookbook that this syntax is valid. I never saw
it in Python code (not meaning that I believe it doesn't exist :) ).

As a side note, I remembered then that there are also "else"-Forms of the while
and the for loop which are executed when the loop is left via break (IIRC).

Thank you (and all others) for their answers. I didn't expect to get so many.
Btw, Greg, the .count approach is much nicer than ".find != -1".


More information about the Python-list mailing list