python中怎么返回指定查找字符的位置

在一个长string中搜索某个字符串,比如搜索“test”,我用find只能返回第一个查到的位置,但我想看到比如第3次出现test的位置,但find的参数除了搜索文本,只有start和end,但我不太清楚大概位置,请问有什么其他函数可以指定返回搜多到第几次出现搜索条件的位置,这样的功能吗?

Python编程中对字符串进行搜索查找,并返回字符位置,案例代码如下:

# multiple searches of a string for a substring     
# using s.find(sub[ ,start[, end]])     
#以下面test这段文本为例
text = 'MSKSASPKEPEQLRKLFIGGLSFETTDESLRSAHFESSSYGSAGRRF'    
##查找上面文本中的SA字符串     
search = 'SA'    
start = 0    
while  True:     
    index = text.find(search, start)     
    # if search string not found, find() returns -1     
    # search is complete, break out of the while loop     
    if index == -1:     
        break    
    print( "%s found at index %d"  % (search, index) )     
    # move to next possible start position     
    start = index  + 1    
 //运行结果:
 #SA found at index 3
 #SA found at index 31
 #SA found at index 41
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2018-02-26

用re吧


>>> import re
>>> word = "test"
>>> s = "test abcd test 1234 testcase testsuite"
>>> [m.start() for m in re.finditer(word, s)]
[0, 10, 20, 29]

本回答被提问者和网友采纳
第2个回答  2013-10-25
>>> def find_pos(str, tobefind):
...     L = len(tobefind)
...     def xiter():
...         for i, c in enumerate(str):
...             if c==tobefind[0] and str[i:i+L] == tobefind:
...                 yield i
...     return list(xiter())
... 
>>> find_pos('test test tst testa testb', 'test')
[0, 5, 14, 20]
>>>

第3个回答  2013-10-25
#常规循环版
def findn(cs,ms,n=1):
    finalLoc=0
    matchLen=len(ms)
    for i in range(n):
        midLoc=cs.index(ms)
        cs=cs[(midLoc+matchLen):]
        if i==0:
            finalLoc+=midLoc
        else:
            finalLoc+=midLoc+matchLen
    return finalLoc

#递归版
def findn(cs,ms,n=1,loc=0):
    if n==1:
        return loc+cs.index(ms)
    else:
        start=cs.index(ms)+len(ms)
        return findn(cs[start:],ms,n-1,start+loc)


print findn('abaabbbbbab','a',3)

#生成器版
def findn(cs,ms,loc=0):
    nloc=cs.find(ms)
    if nloc!=-1:
        start=nloc+len(ms)
        yield nloc+loc
        for i in findn(cs[start:],ms,start+loc):
            yield i
print list(findn('aaaababbbabab','ab'))

相似回答