Reputation: 1892
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
Upvotes: 27
Views: 16369
Reputation: 60014
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.
Upvotes: 14
Reputation: 109
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.
Upvotes: 3
Reputation: 43265
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
Upvotes: 49