Python – Let’s count a word in a string

Hi, I guess this is not the best practice but it works ­čÖé

Let’s count “cat” in a given string.

mystery_string = "why cat wy dog cat cacacat cacacat o cat bye cat cat"
uzunluk_my_string = len(mystery_string)
cat_sayisi = 0
#print(uzunluk_my_string)
for i in range(0,uzunluk_my_string):
    #print(i)
    if mystery_string[i] == "c":
        #print(i," ",mystery_string[i])
        if mystery_string[i+1] == "a":
            if mystery_string[i+2] == "t":
                cat_sayisi = cat_sayisi + 1
                #print(cat_sayisi)
            #else:
                #break
        #else:
            #break

print(cat_sayisi)

# The output is 7

Leave a Reply

Your email address will not be published. Required fields are marked *