在字符串python中查找vs操作

时间:2013-08-26 06:20:11

标签: python

我需要在字符串中找到模式,发现我们可以使用或查找。谁能告诉我哪一个会更好/快速的字符串。我不需要找到模式索引,因为find也可以返回模式的索引。

temp = "5.9"
temp_1 = "1:5.9"
>>> temp.find(":")
-1
>>> if ":" not in temp:
    print "No"

No 

3 个答案:

答案 0 :(得分:27)

使用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

答案 1 :(得分:6)

绝对使用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

它也更具可读性。

Here's a documentation link about the keyword,还有related question

答案 2 :(得分:1)

使用in会更快,因为使用in只提供模式,而如果你使用find它会给你模式以及它的索引,所以与in相比,计算字符串索引需要一些额外的时间。但是如果你没有处理大数据,那么它对你使用的东西很重要。