您的位置:首页 > 编程语言 > Python开发

Python中字符串查找效率比较

2015-05-06 21:39 344 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐