["python","string"]
Determining how many times a substring occurs in a string in Python

I am trying to figure out how many times a string occurs in a string. For example: nStr = '000123000123' Say the string I want to find is 123. Obviously it occurs twice in nStr but I am having trouble implementing this logic into Python. What I have got at the moment: pattern = '123' count = a = 0 while pattern in nStr[a:]: a = nStr[a:].find(pattern)+1 count += 1 return count The answer it should return is 2. I'm stuck in an infinite loop at the moment. I was just made aware that count is a much better way to do it but out of curiosity, does anyone see a way to do it similar to what I have already got?
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)