这就是如何设计index()
;仅返回第一次出现。
如果你想查找所有的事件,你必须在循环或递归中多次调用它。我们这样做之前,你应该知道,你可以提供start
和end
参数来定义在哪里的例句搜索:
>>> "cat cat".index("cat")
0
>>> "cat cat".index("cat", 1) # start search from index 1
4
>>> "cat cat".index("cat", 1, 4) # ...and stop search right before index 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
这样,我们才能避免在同一个索引所有的时间在我们的循环:
s = "cat cat"
indexes = []
index = -1
while True:
try:
index = s.index("cat", index + 1)
except ValueError:
break
indexes.append(index)
print(indexes)
# Output: [0, 4]
这里是一个递归的生成,如果你想要去幻想:
def find_indices(s, sub, start=0, end=None):
if end is None:
end = len(s)
try:
start = s.index(sub, start, end)
except ValueError:
return
yield start
yield from find_all_indexes(s, sub, start + 1, end)
使用(也仍然支持start
个end
参数):
>>> list(find_indices("cat cat cat cat", "cat"))
[0, 4, 8, 12]
或者,如果你想有一个非递归生成器,你可以使用原来的while
循环并将其yield
,而不是追加到一个列表:
def find_indices(s, sub, start=0, end=None):
if end is None:
end = len(s)
start -= 1
while True:
try:
start = s.index(sub, start + 1, end)
except ValueError:
break
yield start
完全一样用法如前。
:生成指数发电机因为'index'函数就是这么做的。 –
@Chris_Rands:这不是一个列表,而是一个字符串,它是一个*子字符串* ...但是可能在某处存在一个重复。 –
@WillemVanOnsem你是对的,被愚弄,因为OP做了一个列表,但没有使用它,也许这个代替:http://stackoverflow.com/questions/3873361/finding-multiple-occurrences-of-a-string -within-A-字符串中的Python –