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
  • 2
    Strings have a builtin method for that: docs.python.org/2/library/stdtypes.html#str.count Commented Jun 21, 2015 at 19:39
  • Intendation is important in Python. Commented Jun 21, 2015 at 19:40
  • 3
    A good question starts with a good title. Commented Jun 21, 2015 at 19:40
  • 1
    Do you need overlapping strings? eg: What's the correct count for "dadadad"? Commented Jun 21, 2015 at 19:43
  • 2
    Another tip: the pythonic naming convention is snake_case instead of camelCase. Commented Jun 21, 2015 at 19:47

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

2 Comments

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

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.