Skip to content
Advertisement

Remove character from a string and list all possible permutations

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.

  1. I cannot write to a file as I just get errors.

Advertisement

Answer

You can:

  1. count the amount of asterisks in the string.
  2. Create the product of all letters with as many repetitions as given in (1).
  3. Replace each asterisk (in order) with the matching letter:
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:

  1. Instead of creating a string of all letters, just use the string module.
  2. This converts the product’s tuples to iterators for easy handling of sequential replacing of each letter.
  3. Uses the join method to create the new string out of the input string.
  4. The above code simply prints each permutation. You can of course replace it with writing to a file or anything else you desire.
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement