Skip to content Skip to sidebar Skip to footer

Python: Finding A Substring Within A String

I'm trying to write a program which counts how many times a substring appears within a string. word = 'wejmfoiwstreetstreetskkjoih' streets = 'streets' count = 0 if streets in wor

Solution 1:

Can be done using a regex

>>>import re>>>text = 'streetstreets'>>>len(re.findall('(?=streets)', text))
2

From the docs:

(?=...)

Matches if ... matches next, but doesn’t consume any of the string. This is called a lookahead assertion. For example, Isaac (?=Asimov) will match 'Isaac ' only if it’s followed by 'Asimov'.

Solution 2:

Quick and dirty:

>>>word = "wejmfoiwstreetstreetskkjoih">>>streets = "streets">>>sum(word[start:].startswith(streets) for start inrange(len(word)))
2

Solution 3:

A generic (though not as elegant) way would be a loop like this:

def count_substrings(stack, needle):
    idx =0
    count = 0while True:
        idx = stack.find(needle, idx) + 1# next time look after this idxif idx <= 0:
            break
        count += 1return count

My measurement shows that it's ~8.5 times faster than the solution with startswith for every substring.

Post a Comment for "Python: Finding A Substring Within A String"