我需要在字符串中找到模式,发现我们可以使用in或find。请问有人能建议我哪个更好/更快吗?我不需要找到模式的索引,因为find也可以返回模式的索引。
temp = "5.9"
temp_1 = "1:5.9"
>>> temp.find(":")
-1
>>> if ":" not in temp:
print "No"
No
我需要在字符串中找到模式,发现我们可以使用in或find。请问有人能建议我哪个更好/更快吗?我不需要找到模式的索引,因为find也可以返回模式的索引。
temp = "5.9"
temp_1 = "1:5.9"
>>> temp.find(":")
-1
>>> if ":" not in temp:
print "No"
No
使用in
,速度更快。
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
一定使用in
。它就是为此目的而制作的,而且速度更快。
str.find()
不应该用于此类任务。它用于查找字符串中字符的索引,而不是检查一个字符是否在字符串中。因此,它会慢得多。
如果您处理的数据更大,则真正想要使用in
以达到最大效率:
$ 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
它也更易读。
这里是关于该关键字的文档链接,以及一个相关问题。
python -m timeit -s "temp = '1'*10000 + ':' " "':' not in temp"
,第一部分在开始时只执行一次(-s
表示设置),只有第二部分被计时。 - flornquake使用in会更快,因为它只提供模式,而如果你使用find,它会给你模式以及它的索引,所以计算字符串的索引会花费额外的时间。然而,如果你不处理大数据,则无论使用哪种方法都没有关系。
if substring in text: ...
是平易近人的英语。 - Bakuriu