Reputation: 13
I'm trying to go through a string and every time I come across an asterisk (*
) replace it with every letter in the alphabet. Once that is done and another asterisk is hit, do the same again in both positions and so on. if possible saving these permutations to a .txt file or just printing them out. This is what I have and don't know where to go further than this:
alphabet = "abcdefghijklmnopqrstuvwxyz"
for i in reversed("h*l*o"):
if i =="*":
for j in ("abcdefghijklmnopqrstuvwxyz"):
Right I have some more challenges for some of the solutions below that im trying to use.
Upvotes: 1
Views: 282
Reputation: 8010
Interesting problems. I assume you mean the cartesian product and not "permutations".
I would use itertools:
string = "h*l*o"
import itertools
# for every combination of N letters
for letters in itertools.product(alphabet, repeat=string.count('*')):
# iterate over the letters
letter_iter = iter(letters)
# replace every * with the next instance
print(''.join(i if i!='*' else next(letter_iter) for i in string))
Upvotes: 2
Reputation: 19414
You can:
count
the amount of asterisks in the string.product
of all letters with as many repetitions as given in (1).import string
import itertools
s = "h*l*o"
num_of_asterisks = s.count('*')
for prod in itertools.product(string.ascii_lowercase, repeat=num_of_asterisks):
it = iter(prod)
new_s = ''.join(next(it) if c == '*' else c for c in s)
print(new_s)
Notes:
string
module.join
method to create the new string out of the input string.Upvotes: 3