"str.contains(part)" or alternatives?

Steve Holden sholden at holdenweb.com
Wed Sep 11 16:42:17 EDT 2002


"Stefan Schwarzer" <sschwarzer at sschwarzer.net> wrote in message
news:alo8jr$l04$1 at news.online.de...
> 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?
>

I think the current proposal is to move to

    if ll in s:

for this construct. Happy?

regards
-----------------------------------------------------------------------
Steve Holden                                  http://www.holdenweb.com/
Python Web Programming                 http://pydish.holdenweb.com/pwp/
Previous .sig file retired to                    www.homeforoldsigs.com
-----------------------------------------------------------------------






More information about the Python-list mailing list