You can use in
to test if a substring appears:
>>> 'code' in 'recoded'
True
This removes the need to loop over the string.
You can generate your test strings by looping over all letters in the alphabet; Python already has the latter available for you at string.ascii_lowercase
and a list comprehension:
import string
possibilities = ['co{l}e'.format(l) for l in string.ascii_lowercase]
count = 0
for possibility in possibilities:
if possibility in inputstring:
count += 1
You could also just test for co
appearing, and see if there is a letter e
further along. You can use the str.find()
method to find the position of an occurrence and search from there; str.find()
takes a starting position to search for the next match:
count = 0
start = 0
while True:
position = inputstring.find('co')
if position == -1:
# not found, end the search
break
if len(inputstring) > position + 2 and inputstring[position + 2] == 'e':
count += 1
start = position + 1
However, most experienced programmers will use regular expressions to find such matches:
import re
count = len(re.find_allfindall(r'co[a-z]e', inputstring))
Here the expression uses [a-z]
to match a single character as a class, anything in that series (so letters from a
to z
) would match. The re.findall()
function returns a list of all matches found in the input string, so all you have to do then is take the len()
length of that list to get a count.