"str.contains(part)" or alternatives?

Skip Montanaro skip at pobox.com
Wed Sep 11 16:40:51 EDT 2002


    >>> 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.  Use this
instead:

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

Also note that in 2.3 the semantics of the 'in' operator will change to make
this sort of test more natural:

    % python
    Python 2.3a0 (#86, Sep  4 2002, 21:13:00) 
    [GCC 2.96 20000731 (Mandrake Linux 8.1 2.96-0.62mdk)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> 'll' in 'hello'
    True

-- 
Skip Montanaro
skip at pobox.com
consulting: http://manatee.mojam.com/~skip/resume.html




More information about the Python-list mailing list