本文介绍了什么是更快的操作,re.match/search 或 str.find?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一次性字符串搜索,使用 str.find/rfind 是否比使用 re.match/search 更快?

For one off string searches, is it faster to simply use str.find/rfind than to use re.match/search?

也就是说,对于给定的字符串 s,我应该使用:

That is, for a given string, s, should I use:

if s.find('lookforme') > -1:
    do something

if re.match('lookforme',s):
    do something else

?

推荐答案

问题:使用 timeit 最好回答哪个更快.

The question: which is faster is best answered by using timeit.

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

因此,您不仅应该使用 in 运算符,因为它更易于阅读,而且速度也更快.

So not only should you use the in operator because it is easier to read, but because it is faster also.

这篇关于什么是更快的操作,re.match/search 或 str.find?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 20:03