How to make a python script that gives you every iteration of a string from a pattern

Advertisements

So I’m trying to make a python script that takes a pattern (ex: c**l) where it’ll return every iteration of the string (* = any character in the alphabet)…

So, we get something like: caal, cbal, ccal and so forth.
I’ve tried using the itertools library’s product but I haven’t been able to make it work properly. So after 2 hours I’ve decide to turn to Stack Overflow.

Here’s my current code. It’s not complete since I feel stuck

alphabet = list('abcdefghijklmnopqrstuvwxyz')

wildChar = False
tmp_string = ""
combinations = []

if '*' in pattern:
    wildChar = True
    tmp_string = pattern.replace('*', '', pattern.count('*')+1)

if wildChar:
    tmp = []
    for _ in range(pattern.count('*')):
        tmp.append(list(product(tmp_string, alphabet)))
    
        for array in tmp:
            for instance in array:
                
                combinations.append("".join(instance))
                tmp = []

print(combinations)

>Solution :

You could try:

from itertools import product
from string import ascii_lowercase

pattern = "c**l"
repeat = pattern.count("*")
pattern = pattern.replace("*", "{}")
for letters in product(ascii_lowercase, repeat=repeat):
    print(pattern.format(*letters))

Result:

caal
cabl
cacl
...
czxl
czyl
czzl

Leave a Reply Cancel reply