ChrisMcJava
ChrisMcJava

Reputation: 2293

find not just the first index of a substring in a string - python 2.7

so I know that str.index(substring, begin, end=len(str)) returns the first index of a substring starting from begin. Is there a better (faster, cleaner) way of getting the next index of a string than simply changing the begin index to be that of the last occurance + the length of the target string? i.e. (this is the code i'm running)

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

output:

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

Upvotes: 3

Views: 141

Answers (2)

ndpu
ndpu

Reputation: 22571

You can create a simple generator:

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]

Upvotes: 2

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251146

You can use re.finditer and a list comprehension:

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

The match objects have two useful methods .start() and .end(), these return the start and end indices of sub-string matched by the current group.

Another way using slicing:

>>> [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]

Upvotes: 4

Related Questions