-3

In my program I'm using count=strr2.lower().count("ieee") to calculate the number of occurrences in the following string,

"i love ieee and ieeextream is the best coding competition ever"

In here it counts "ieeextream" is also as one occurrence which is not my expected result. The expected output is count=1

So are there any method to check only for "ieee" word or can we change the same code with different implementation? Thanks for your time

INDRAJITH EKANAYAKE
  • 3,894
  • 11
  • 41
  • 63

2 Answers2

3

If you are trying to find the sub-string as a whole word present in the original string, then I guess, this is what you need :

count=strr2.lower().split().count("ieee")
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
1

If you want to count only whole words, you can use a regular expression, wrapping the word to be found in word-boundary characters \b. This will also work if the word is surrounded by punctuation.

>>> import re
>>> s = "i love IEEE, and ieeextream is the best coding competition ever"
>>> len(re.findall(r"\bieee\b", s.lower()))
1
tobias_k
  • 81,265
  • 12
  • 120
  • 179