24

I need to find pattern into string and found that we can use in or find also. Could anyone suggest me which one will be better/fast on string. I need not to find index of pattern as find can also return the index of the pattern.

temp = "5.9"
temp_1 = "1:5.9"
>>> temp.find(":")
-1
>>> if ":" not in temp:
    print "No"

No 
user765443
  • 1,856
  • 7
  • 31
  • 56

3 Answers3

45

Use in , it is faster.

dh@d:~$ python -m timeit 'temp = "1:5.9";temp.find(":")'
10000000 loops, best of 3: 0.139 usec per loop
dh@d:~$ python -m timeit 'temp = "1:5.9";":" in temp'
10000000 loops, best of 3: 0.0412 usec per loop
DhruvPathak
  • 42,059
  • 16
  • 116
  • 175
13

Definitely use in. It was made for this purpose, and it is faster.

str.find() is not supposed to be used for tasks like this. It's used to find the index of a character in a string, not to check whether a character is in a string. Thus, it will be much slower.

If you're working with much larger data, then you really want to be using in for maximum efficiency:

$ python -m timeit -s "temp = '1'*10000 + ':' " "temp.find(':') == -1"
100000 loops, best of 3: 9.73 usec per loop
$ python -m timeit -s "temp = '1'*10000 + ':' " "':' not in temp"
100000 loops, best of 3: 9.44 usec per loop

It's also much more readable.

Here's a documentation link about the keyword, and also a related question.

Community
  • 1
  • 1
TerryA
  • 58,805
  • 11
  • 114
  • 143
  • What "can be an issue"? Your example shows that there is little difference in performance when working with large strings. – flornquake Aug 26 '13 at 06:53
  • @flornquake I have clarified – TerryA Aug 26 '13 at 06:55
  • My point was that the (percenage) difference does not seem to be all that big when working with large strings. I think you forgot the `-s` flag before the first string. – flornquake Aug 26 '13 at 07:08
  • @flornquake What does that do :o? – TerryA Aug 26 '13 at 07:10
  • If you write `python -m timeit -s "temp = '1'*10000 + ':' " "':' not in temp"`, the first part is executed once at the beginning (`-s`for setup) and only the second part is timed. – flornquake Aug 26 '13 at 07:14
3

Using in will be faster as using in provides only pattern while if you use find it will give you pattern as well as its index so it will take some extra time in computing the index of the string as compared to in. However if you are not dealing with large data then it dosent matter what you use.

Nelson Menezes
  • 109
  • 2
  • 8