Momo
Momo

Reputation: 45

Counting sub-string occurrences in a string

I want to write a loop in python that checks the first three letter from 0-2 for a certain word then checks the next letters from 1-3 for the same word.

This is my code so far, it always just prints out 1 after any input.

Count = 0
start = 0
end = start + 2
word = 'dad'
string = input('Type in a word')

for word in string[start-end]:
    if word in string:
         Count = Count + 1
    start = start + 1

print (Count)

Could someone help me please?

Upvotes: 0

Views: 1559

Answers (2)

Harry
Harry

Reputation: 318

I have tried to optimise the code. This code works for overlapping while for non-overlapping matches count can be used.

string = 'dadada'
substring = 'dad'
results = 0
sub_len = len(substring)
for i in range(len(string)):
    if string[i:i+sub_len] == substring:
        results += 1
print results

alternative

Although this process suits the OP but for future visitors its better to have advance alternatives. As suggested in the comment section.

import re
results = sum(1 for _ in re.finditer('(?=dad)', 'dadada'))

this functionality uses positive lookahead of regex for finding the solution the reason of the use sum and for loop is to find the number of iteration as finditer returns iterator.

user can also try len(list(re.finditer('(?=dad)', 'dadada'))) which will convert the iterator to list and find the length.

non-re alternative

string = 'dadada'
sub = 'dad'
print len([n for n in xrange(len(string)) if string.find(sub, n) == n])

This is an implementation with custom method find function of str. If we remove len we can get the list of indexes.

Upvotes: 2

Islam El-Ashry
Islam El-Ashry

Reputation: 72

    word = 'dad'
    string = input('Type in a word')
    print (string.count(word))

I think that's all you looking for

Upvotes: 0

Related Questions