TransWikia.com

Counting the occurrences of a substring in a string python

Stack Overflow Asked by Indrajith Ekanayake on February 24, 2021

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

2 Answers

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")

Correct answer by Arkistarvh Kltzuonstev on February 24, 2021

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"bieeeb", s.lower()))
1

Answered by tobias_k on February 24, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP