Testing if string contains a substring
Alex Martelli
aleax at aleax.it
Wed Apr 23 10:50:21 EDT 2003
Frantisek Fuka wrote:
> I want a simple test to see if str contains any occurences of substr. I
> am currently using this:
>
> import string
> if string.find(str,substr) + 1:
> ...do something...
>
> But it somehow looks "ugly" to me. Is there more "standard" way to test
> this?
With the close-to-beta-release Python 2.3, sure:
[alex at lancelot src]$ python2.3
Python 2.3a2+ (#11, Mar 28 2003, 12:17:11)
[GCC 3.2 (Mandrake Linux 9.0 3.2-1mdk)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 'foo' in 'barfooble'
True
>>> 'gzap' in 'barfooble'
False
>>>
and more generally, "needle in haystack".
However, such new functionality doesn't get back-ported to previous
releases of Python, such as 2.2.*. In all Python releases from 1,6
included to 2.3 excluded, "needle.find(haystack) > 0" is the idiom.
Module string is needed if you want to use antediluvian versions of
Python, such as 1.5.2, where strings didn't have methods.
Alex
More information about the Python-list
mailing list