python - 不仅查找字符串中子字符串的第一个索引 - python 2.7

标签 python string python-2.7 indexing

所以我知道 str.index(substring, begin, end=len(str)) 返回从 begin 开始的子字符串的第一个索引。有没有比简单地将开始索引更改为最后一次出现的索引 + 目标字符串的长度更好(更快、更干净)的方法来获取字符串的下一个索引?即(这是我正在运行的代码)

full_string = "the thing is the thingthe thing that was the thing that did something to the thing."
target_string = "the thing"

count = full_string.count(target_string)
print 'Count:', count

indexes = []
if (count > 0):
    indexes.append(full_string.index(target_string))
    i = 1
    while (i < count):
        start_index = indexes[len(indexes) - 1] + len(target_string) 

        current_index = full_string.index(target_string, start_index)
        indexes.append(current_index)
        i = i + 1

print 'Indexes:', indexes

输出:

Count: 5
Indexes: [0, 13, 22, 41, 73]

最佳答案

您可以使用 re.finditer和列表理解:

>>> import re
>>> [m.start() for m in re.finditer(target_string, full_string)]
[0, 13, 22, 41, 73]

match objects有两个有用的方法.start().end() , 这些返回与当前组匹配的子字符串的开始和结束索引。

另一种使用切片的方法:

>>> [i for i in xrange(len(full_string) - len(target_string) + 1)
                           if full_string[i:i+len(target_string)] == target_string]
[0, 13, 22, 41, 73]

关于python - 不仅查找字符串中子字符串的第一个索引 - python 2.7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21442072/

相关文章:

python - 将 python for 循环的一次迭代的输出通过管道传输到另一个脚本

regex - Python - 检查字符串是否在更大的字符串中

python - 在 Python 中将 pdf 转换为 html

objective-c - Swift 将十六进制字符串或字符转换为整数

java - 匹配两个字符串,一个与 x,另一个与任意字符

regex - 如何找出与给定正则表达式匹配的字符串的最大和最小长度

python-2.7 - Selenium Python属性错误: 'WebElement' object has no attribute 'select_by_visible_text'

python - 在Python上修改全局变量传入参数函数

python - 按模式读取文件

python - pyqt - 阻止对图像和 JavaScript 文件的请求