Python – Return the number of times that the string “code” appears anywhere in the given string

pythonstring

Return the number of times that the string "code" appears anywhere in
the given string, except we'll accept any letter for the 'd', so
"cope" and "cooe" count.

I have achieved this with the following code using regular expressions:

import re


def count_code(str):
    exp = '^co[a-z|A-Z]e$'
    count = 0
    for i in range(len(str) - 1):
        if re.match(exp, str[i:i + 4]):
            count = count + 1

    return count

print count_code('aaacodebbb')  # prints 1
print count_code('codexxcode')  # prints 2
print count_code('cozexxcope')  # prints 2

Is there any other way of achieving this without using regular expressions?

Best Solution

One way is you can make every possible string with co*e where * is any alphabet

Like

x=["co"+i+"e" for i in string.lowercase]

Then iterate

for i in x:
    if i in <your string>:
        count+=<your string>.count(i)