user3141639
user3141639

Reputation: 11

Count each time a string appears in a longer string, Python

I'd like to count if a string can be found within a longer string.

For example, if i have the string: "Heyheyheyhey". I'd like to check how many times the part "ey" is in the string, and get the count 4. Lets say that i have this string in a list aswell.

I tried this, but it works just if the part appears one time in the string.

For word in list:
   count = 0
   If 'ey' in word:
       count +=1

I thought exchanging the if to a while would work, but obviously not. Any tips?

this is all in PYTHON 3.x.

Upvotes: 0

Views: 92

Answers (1)

dawg
dawg

Reputation: 103884

With the string method count:

>>> 'Heyheyheyhey'.count('ey')
4

With a regex:

>>> import re
>>> len(re.findall(r'ey', 'Heyheyheyhey'))
4

Edit

If you want to match multiple things, you can use a list comprehension:

>>> s='Hey hi how'
>>> sum(1 for i in range(0,len(s)) if s[i] in 'eyio')
4

Or a regex:

>>> len(re.findall(r'e|y|i|o', s))
4

Upvotes: 1

Related Questions