"str.contains(part)" or alternatives?

Stefan Schwarzer sschwarzer at sschwarzer.net
Wed Sep 11 16:23:02 EDT 2002


Hello all

I would like to get your thoughts on testing if a string contains another.

To do something dependent on whether a part is contained in another string, the
following code is familiar to me:

 >>> s = 'Hello'
 >>> if s.find('ll') != -1:
...     do_something_if_found()
... else:
...     do_something_if_not_found()

However, I dislike the test for the special value -1; that reminds me of error
code checking. On the other hand, using exceptions could look like

 >>> try:
...     s.index('ll')
...     do_something_if_found()
... except ValueError:
...     do_something_if_not_found()

This has the problem that a ValueError raised in do_something_if_found() may give
the false impression that the substring isn't contained in the string s. Moreover,
that code doesn't represent my thoughts very well. (Maybe I could say that better
if I were a native English speaker :) ).

I would like something analogous to .startswith and .endswith:

 >>> s = 'Hello'
 >>> if s.contains('ll'):
...     do_something_if_found()
... else:
...     do_something_if_not_found()

Do you have other suggestions how to do the test easily without using special
values? Should a .contains method be part of string objects in future Python
versions? What do you think?

Stefan




More information about the Python-list mailing list