这是简单的迭代解决方案的更多Pythonic版本:
def find_nth(haystack, needle, n):
start = haystack.find(needle)
while start >= 0 and n > 1:
start = haystack.find(needle, start+len(needle))
n -= 1
return start
例:
>>> find_nth("foofoofoofoo", "foofoo", 2)
6
如果要查找的第n个重叠出现needle,可以用1代替,增加len(needle),如下所示:
def find_nth_overlapping(haystack, needle, n):
start = haystack.find(needle)
while start >= 0 and n > 1:
start = haystack.find(needle, start+1)
n -= 1
return start
例:
>>> find_nth_overlapping("foofoofoofoo", "foofoo", 2)
3
这比Mark的版本更容易阅读,并且不需要拆分版本或导入正则表达式模块的额外内存。与各种方法不同,它还遵守python Zen中的一些规则re:
简单胜于复杂。
扁平比嵌套更好。
可读性很重要。