Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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"):

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading