4

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?

8

1 Answer 1

9

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)))
2
  • Can u please tell me where to use the last code? i tried including it in my code but i'm not getting the desired output.
    – coder123
    Jun 22, 2015 at 3:39
  • 1
    You'll have to use the last line as an expression, for example num_repeats = sum(haystack[i:i+len(needle)] == needle for i in range(len(haystack))) and then use num_repeats variable as you would like. (such as printing it etc) Jun 22, 2015 at 6:24

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.