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?
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)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With