在Python中查找string的示例
我试图find一些例子,但没有运气。 有谁知道网上的一些例子? 我想知道它什么时候找不到,以及如何指定从开始到结束,我猜将会是0,-1。
你也可以使用str.index : 
 >>> 'sdfasdf'.index('cc') Traceback (most recent call last): File "<pyshell#144>", line 1, in <module> 'sdfasdf'.index('cc') ValueError: substring not found >>> 'sdfasdf'.index('df') 1 
 我不确定你在找什么,你的意思是find() ? 
 >>> x = "Hello World" >>> x.find('World') 6 >>> x.find('Aloha'); -1 
从这里 :
  str.find(sub [,start [,end]]) 
 返回find子string的string中的最小索引,使得sub包含在[start,end]范围内。 可选参数开始和结束被解释为切片符号。 如果没有find子项,则返回-1。 
所以,一些例子:
 >>> str = "abcdefioshgoihgs sijsiojs " >>> str.find('a') 0 >>> str.find('g') 10 >>> str.find('s',11) 15 >>> str.find('s',15) 15 >>> str.find('s',16) 17 >>> str.find('s',11,14) -1 
老实说,这就是我刚刚在命令行打开Python并开始搞乱的情况:
  >>> x = "Dana Larose is playing with find()" >>> x.find("Dana") 0 >>> x.find("ana") 1 >>> x.find("La") 5 >>> x.find("La", 6) -1 
Python的解释器使得这种实验变得简单。 (其他语言也有类似的翻译)
如果要search文本中string的最后一个实例,可以运行rfind。
例:
  s="Hello" print s.rfind('l') 
输出:3
*不需要import
完整的语法:
 stringEx.rfind(substr, beg=0, end=len(stringEx)) 
 find( sub[, start[, end]]) 
返回find子string的string中的最小索引,使得sub包含在[start,end]范围内。 可选参数开始和结束被解释为切片符号。 如果未find子项,则返回-1。
从文档 。
尝试这个:
 with open(file_dmp_path, 'rb') as file: fsize = bsize = os.path.getsize(file_dmp_path) word_len = len(SEARCH_WORD) while True: p = file.read(bsize).find(SEARCH_WORD) if p > -1: pos_dec = file.tell() - (bsize - p) file.seek(pos_dec + word_len) bsize = fsize - file.tell() if file.tell() < fsize: seek = file.tell() - word_len + 1 file.seek(seek) else: break