Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of times a particular string appears in a given word

Tags:

python

How to write a program that prints the number of times a particular string appears in a given word. For example: if I'm looking for the string 'dad' in a word 'asdadgfrdad' output should be 2.

def numStrings(a):
    strings = 'dad'
    result = 0
    for char in a:
        if char in strings:
            result = result + 1
    print result

numStrings("asdadgfrdad")

But this gives me the number of times the letters d,a are present in the given word. How to correct this?

like image 447
coder123 Avatar asked Jan 09 '23 02:01

coder123


1 Answers

The short and simple pythonic way to do it would be

'asdadgfrdad'.count('dad')

However, your answer may or may not be what you expect when you look at something like 'dadad'.count('dad') which returns 1 instead of 2. This is because str.count returns the number of non-overlapping occurrences of substring. On the other hand, if you want to find the number of overlapping substrings, you'll have to use the following code:

haystack = 'dadad'
needle = 'dad'
sum(haystack[i:i+len(needle)] == needle for i in range(len(haystack)))
like image 141
Jay Bosamiya Avatar answered Jan 10 '23 17:01

Jay Bosamiya