【问题标题】:find not just the first index of a substring in a string - python 2.7不仅找到字符串中子字符串的第一个索引 - python 2.7
【发布时间】:2014-01-29 20:35:40
【问题描述】:

所以我知道 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]

【问题讨论】:

    标签: python string python-2.7 indexing


    【解决方案1】:

    您可以使用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]
    

    【讨论】:

      【解决方案2】:

      您可以创建一个简单的生成器:

      def gsubstrings(string, sub):
           i = string.find(sub)
           while i >= 0:
               yield i
               i = string.find(sub, len(sub) + i)
      
      >>> list(gsubstrings(full_string, target_string))
      [0, 13, 22, 41, 73]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-29
        • 1970-01-01
        • 2020-02-14
        • 1970-01-01
        • 2014-03-17
        • 2020-08-02
        • 1970-01-01
        • 2011-05-29
        相关资源
        最近更新 更多