Testing if string contains a substring

Bengt Richter bokr at oz.net
Wed Apr 23 16:13:08 EDT 2003


On Wed, 23 Apr 2003 14:50:21 GMT, Alex Martelli <aleax at aleax.it> wrote:
[...]
>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.

If needle is a substring to be found in haystack, that seems reversed. I.e.,

 >>> haystack = 'needle-in-haystack with second needle fthoi'
 >>> needle = 'needle'
 >>> haystack.count(needle)
 2
 >>> haystack.find(needle)
 0

And a nit:
 >>> haystack.find(needle) > 0
 0
 >>> haystack.find(needle) >= 0
 1

Were you recently using re to find needles? E.g.,

 >>> import re
 >>> needle = re.compile('needle')
 >>> needle.findall(haystack)
 ['needle', 'needle']

Regards,
Bengt Richter




More information about the Python-list mailing list