Theo Boston
Theo Boston

Reputation: 21

Python 3: finding a set of letters in a string using loops

i'm using python 3 and i would like to know how to count the amount of times a set of 3 letters comes up in a sentence:

con = ""
count = 0
for i in mystery_string:
    if i == "c":
        con = "c" 
    if i == "a" and con == "c":
        con = "ca"   
    if i == "t" and con == "ca":
        con = "cat"
    if con == "cat":
        count +=1
        con = ""
print (count)

this is the code i have so far, however it doesn't seem to work for every case can someone help me

the thing i also need to explain is that i cannot use the builtin function count()

Upvotes: 0

Views: 406

Answers (3)

Glenn Chamberlain
Glenn Chamberlain

Reputation: 11

mystery_string = "my cat your cat"

count = 0

current_search_letter = "c"


    if letter == "c":
        current_search_letter = "a"


    elif letter == "a" and current_search_letter == "a":
        current_search_letter = "t"


    elif letter == "t" and current_search_letter == "t":
        count += 1
        current_search_letter = "c"
    else:
        current_search_letter = "c"
print(count)

Upvotes: 0

prophet-five
prophet-five

Reputation: 559

you can use slicing:

word='cat'
count = 0
for i in range(len(mystery_string)-len(word)+1):
    if mystery_string[i:i+len(word)]==word:
        count +=1
print (count)

Upvotes: 1

Biswadip Mandal
Biswadip Mandal

Reputation: 544

just do the following

mystery_string.count('cat')

Upvotes: 2

Related Questions