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?
Python String count() The count() method returns the number of occurrences of a substring in the given string.
Count Number of Occurrences in a String with .count() method. The method takes one argument, either a character or a substring, and returns the number of times that character exists in the string associated with the method.
Using regular expressions, we can easily check multiple substrings in a single-line statement. We use the findall() method of the re module to get all the matches as a list of strings and pass it to any() method to get the result in True or False.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With