Search code examples
python-3.xlisthexpython-itertoolssubstitution

The most efficient way to produce a list of all possible hexadecimal strings with a specific length and using mask


I have a long string with a length of 32 characters, which has the character "x" for masking. What is the most efficient way to produce a list of all possible hexadecimal strings with a specific length and using mask. We can have more than one character masking (multiple X) For example:

If I use the following string as the input to my program,

my_string = '0011223344x56677889xaabbccddee'

I would like to have the following as the output of the program (iterating from 0 to f for each x on the input string):

all_possible = ['00112233440566778890aabbccddee',
                '00112233441566778890aabbccddee',
                '00112233442566778890aabbccddee',
                  ...
                '0011223344e566778890aabbccddee',
                '0011223344f566778890aabbccddee',
                '00112233440566778891aabbccddee',
                '00112233441566778892aabbccddee',
                '00112233442566778893aabbccddee',
                '00112233443566778894aabbccddee',
                  ...
                '0011223344f56677889faabbccddee'
]

Solution

  • You can use itertools.combinations_with_replacement itertools.product with re.sub:

    import re
    from itertools import product
    
    my_string = "0011223344x56677889xaabbccddee"
    num_x = my_string.count("x")
    
    for c in product("0123456789abcdef", repeat=num_x):
        i = iter(c)
        print(re.sub(r"x", lambda g: next(i), my_string))
    

    Prints:

    00112233440566778890aabbccddee
    00112233440566778891aabbccddee
    00112233440566778892aabbccddee
    00112233440566778893aabbccddee
    00112233440566778894aabbccddee
    00112233440566778895aabbccddee
    00112233440566778896aabbccddee
    
    ...
    
    0011223344d56677889faabbccddee
    0011223344e56677889eaabbccddee
    0011223344e56677889faabbccddee
    0011223344f56677889faabbccddee