[Python-Dev] string find(substring) vs. substring in string

Fredrik Lundh fredrik at pythonware.com
Wed Feb 16 21:08:14 CET 2005


any special reason why "in" is faster if the substring is found, but
a lot slower if it's not in there?

timeit -s "s = 'not there'*100" "s.find('not there') != -1"
1000000 loops, best of 3: 0.749 usec per loop

timeit -s "s = 'not there'*100" "'not there' in s"
10000000 loops, best of 3: 0.122 usec per loop

timeit -s "s = 'not the xyz'*100" "s.find('not there') != -1"
100000 loops, best of 3: 7.03 usec per loop

timeit -s "s = 'not the xyz'*100" "'not there' in s"
10000 loops, best of 3: 25.9 usec per loop

</F>

ps. btw, it's about time we did something about this:

timeit -s "s = 'not the xyz'*100" -s "import re; p = re.compile('not there')" "p.search(s)"
100000 loops, best of 3: 5.72 usec per loop 





More information about the Python-Dev mailing list