How to find index of second occurrence of a phrase in a string in Python 3?
如何(在python 3中)找到字符串中短语第二次出现的索引?到目前为止我的代码是
1 2 | result = string.index("phrase im looking for") print (result) |
它给出了字符串"string"中"短语im looking"的索引。但是,如果"短语im looking for"出现两次,并且我想查找第二次出现的索引(忽略第一次),我该怎么做呢?
您可以按如下步骤查找某些短语的索引,例如:
1 2 3 4 5 6 7 8 | import re mystring ="some phrase with some other phrase somewhere" indices = [s.start() for s in re.finditer('phrase', mystring)] print(indices) %[5, 28] |
所以很明显,第二次出现"短语"的指标是