0

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.

2
  • 1
    I'd suggest tagging this question with the relevant language for some more views. Commented Dec 30, 2013 at 0:00
  • Which language are you talking about? Commented Dec 30, 2013 at 0:01

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Can one or both of these be used to count the number of vokals at the same time? That would be quite nice for me. like: "Heyhi".count('e','y','i') should return 3 or something

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.