Search code examples
pythonpython-3.xcombinationsproductpython-itertools

Change each place in a string to find all possible combinations


The goal is to find all possible combinations if we change one place in a string with some specific characters.

Here's the code I have so far:

from itertools import product

string = "abc123"

char = "def2346789"

for i in range(len(string)):
    for char1 in product(char):
        print(string[:i] + char1 + string[i+1:])

char means characters that will be used in each place.

But I'm confused how it's going to work in the second part, will enjoy to explore the solution.

So the result will be something like this:

dbc123 adc123
ebc123 aec123
fbc123 afc123 
2bc123 a2c123 
3bc123 a3c123
4bc123 a4c123
6bc123 a5c123
7bc123 a6c123
8bc123 a7c123
9bc123 a8c123 etc...

Solution

  • You don't (shouldn't) need to use itertools.product here. That is probably what is confusing you:

    string = "abc123"
    
    char = "def2346789"
    
    for i in range(len(string)):
        for c in char:
            print(string[:i] + c + string[i+1:])