Reputation: 39
I know that I can find a word in a string with
if word in my_string:
But I want to find all "word" in the string, like this.
counter = 0
while True:
if word in my_string:
counter += 1
How can I do it without "counting" the same word over and over again?
Upvotes: 1
Views: 26351
Reputation: 37549
Use regular expressions:
import re
word = 'test'
my_string = 'this is a test and more test and a test'
# Use escape in case your search word contains periods or symbols that are used in regular expressions.
re_word = re.escape(word)
# re.findall returns a list of matches
matches = re.findall(re_word, my_string)
# matches = ['test', 'test', 'test']
print len(matches) # 3
Be aware that this will catch other words that contain your word like testing
. You could change your regex to just match exactly your word
Upvotes: 0
Reputation: 5515
If you want to make sure that it counts a full word like is
will only have one in this is
even if there is an is
in this
, you can split, filter and count:
>>> s = 'this is a sentences that has is and is and is (4)'
>>> word = 'is'
>>> counter = len([x for x in s.split() if x == word])
>>> counter
4
However, if you just want count all occurrences of a substring, ie is
would also match the is in this
then:
>>> s = 'is this is'
>>> counter = len(s.split(word))-1
>>> counter
3
in other words, split
the string at every occurrence of the word, then minus one to get the count.
It's been a long day so I totally forgot but str
has a built-in method for this str.count(substring)
that does the same as my second answer but way more readable. Please consider using this method (and look at other people's answers for how to)
Upvotes: 4
Reputation: 132
String actually already has the functionality you are looking for. You simply need to use str.count(item)
for example.
EDIT: This will search for all occurrences of said string including parts of words.
string_to_search = 'apple apple orange banana grapefruit apple banana'
number_of_apples = string_to_search.count('apple')
number_of_bananas = string_to_search.count('banana')
The following will search for only complete words, just split the string you want to search.
string_to_search = 'apple apple orange banana grapefruit apple banana'.split()
number_of_apples = string_to_search.count('apple')
number_of_bananas = string_to_search.count('banana')
Upvotes: 2
Reputation: 6631
Use the beg
argument for the .find
method.
counter = 0
search_pos = 0
while True:
found = my_string.find(word, search_pos)
if found != -1: # find returns -1 when it's not found
#update counter and move search_pos to look for the next word
search_pos = found + len(word)
counter += 1
else:
#the word wasn't found
break
This is kinda a general purpose solution. Specifically for counting in a string you can just use my_string.count(word)
Upvotes: 2