Python中字符串查找方式有多种,常见的有re.match/search or str.find

用一个例子来说明各种方式的效率如下:


from timeit import timeit
import re

def find(string, text):
    if string.find(text) > -1:
        pass

def re_find(string, text):
    if re.match(text, string):
        pass

def best_find(string, text):
    if text in string:
       pass

print timeit("find(string, text)", "from __main__ import find; string='lookforme'; text='look'")  
print timeit("re_find(string, text)", "from __main__ import re_find; string='lookforme'; text='look'")  
print timeit("best_find(string, text)", "from __main__ import best_find; string='lookforme'; text='look'")



执行结果为:

0.441393852234
2.12302494049
0.251421928406



可以看到效率最高的方式是:if text in string :


参考链接:http://stackoverflow.com/questions/4901523/whats-a-faster-operation-re-match-search-or-str-find