Python:string.find(";foo";)vs";"富",;串起。哪个更快?

Python:string.find(";foo";)vs";"富",;串起。哪个更快?,python,string,Python,String,这两个操作中哪一个应该更快? 我只想检查一个字符串是否在另一个字符串中。我们将忽略大小写、字符串部分、空格等 我假设第一个,因为它只检查存在,如果我是对的,而后者也检查位置。 这两种操作是搜索字符串的最佳标准方法吗 string = "my foo is your bar" if "foo" in string: # do important things if string.find("foo") > -1: #do much more important stuff 您可以尝

这两个操作中哪一个应该更快? 我只想检查一个字符串是否在另一个字符串中。我们将忽略大小写、字符串部分、空格等

我假设第一个,因为它只检查存在,如果我是对的,而后者也检查位置。 这两种操作是搜索字符串的最佳标准方法吗

string = "my foo is your bar"

if "foo" in string:
 # do important things

if string.find("foo") > -1:
 #do much more important stuff

您可以尝试python测试,看:

from timeit import timeit
import re

def find(string, text):
    if string.find(text) > -1:
       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("best_find(string, text)", "from __main__ import best_find; string='lookforme'; text='look'") 
结果是:

0.441393852234
0.251421928406

答案取自。如您所见,“in”是一个更好的选项,以防您想要优化代码。

正如链接副本中所指出的,中的
更快;它不需要像
那样返回位置或
-1
。find()
可以,并且不需要属性查找和函数调用(这需要帧堆栈推送和弹出)。嗯,我想知道为什么我找不到其他问题…请不要在这里从复制程序重新发布答案。这就是我们投票支持的。