Your particular error is that .replace
replaces all occurrences e.g., "*arn*val"
-> "CarnCval"
or "IarnIval"
. You want different letters here. You could use the second nested loop over the alphabet (or use itertools.product()
to generate all possible letter pairs) to fix it but a simpler way is to use regular expressions:
import re
# each `*` corresponds to an ascii lowercase letter
pattern = re.escape(wildcard).replace("\\*", "[a-z]")
matches = list(filter(re.compile(pattern+"$").match, known_words))
Note: it doesn't support escaping *
in the wildcard
.
If input wildcards are file patterns then you could use fnmatch
module to filter words:
import fnmatch
matches = fnmatch.filter(known_words, wildcard)