Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining how many times a substring occurs in a string in Python

Tags:

python

string

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?

like image 959
user1294377 Avatar asked Jul 13 '12 18:07

user1294377


People also ask

How do you count the number of times a substring appears in a String Python?

Python String count() The count() method returns the number of occurrences of a substring in the given string.

How many times a substring appears in a 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.

How do you find multiple substrings in Python?

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.


1 Answers

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) 
like image 67
Ashwini Chaudhary Avatar answered Sep 19 '22 21:09

Ashwini Chaudhary