Determining how many times a substring occurs in a string in Python
Use str.count
:
>>> nStr = '000123000123'
>>> nStr.count('123')
2
A working version of your code:
nStr = '000123000123'
pattern = '123'
count = 0
flag = True
start = 0
while flag:
a = nStr.find(pattern, start) # find() returns -1 if the word is not found,
#start i the starting index from the search starts(default value is 0)
if a == -1: #if pattern not found set flag to False
flag = False
else: # if word is found increase count and set starting index to a+1
count += 1
start = a + 1
print(count)
The problem with count()
and other methods shown here is in the case of overlapping substrings.
For example: "aaaaaa".count("aaa")
returns 2
If you want it to return 4 [(aaa)aaa, a(aaa)aa, aa(aaa)a, aaa(aaa)
] you might try something like this:
def count_substrings(string, substring):
string_size = len(string)
substring_size = len(substring)
count = 0
for i in xrange(0,string_size-substring_size+1):
if string[i:i+substring_size] == substring:
count+=1
return count
count_substrings("aaaaaa", "aaa")
# 4
Not sure if there's a more efficient way of doing it, but I hope this clarifies how count()
works.
import re
pattern = '123'
n =re.findall(pattern, string)
We can say that the substring 'pattern' appears len(n) times in 'string'.