Search code examples
pythonpython-itertools

Append itertools.product() results to variable in Python


I am trying to append every possible two-digit combination to the end of each string in a list.

The strings are each eight characters, and the digits should replace the seventh and eighth characters.

I am using itertools.product() to generate these two-digit combos, but I am not sure how to then append these combinations to strings. I tried using join(), but that sandwiches the string between each of the two digits.

My next attempt is below but doesn't work because you cannot concatenate 'str' and 'itertools.product' objects.

for p in passwords:
    candidates += list(p[:6] + itertools.product(string.digits, string.digits))

So, passwords looks like this

['american', 'japanese']

and the output should be

['americ00', 'americ01', 'americ02', …, 'japane98', 'japane99']

Solution

  • Since you're just counting, the product isn't necessary This could be abbreviated to:

     lst = ['american', 'japanese']
     candidates = ['{}{:02d}'.format(e[:6], i) for e in lst for i in range(100)]
    

    Which is alanalgous to the loop

    candidates = []
    for e in lst:
        for i in range(100):
            candidates.append('{}{:02d}'.format(e[:6], i))
    

    If really want product for one reason or another:

    ['{}{}{}'.format(e[:6], i, j) for e in lst for i, j in itertools.product(string.digits, string.digits)]
    

    This can also generalize to a product with more arguments

    [e[:6] + ''.join(pr) for e in lst for pr in itertools.product(string.digits, string.digits, string.digits)]