生成具有特定长度并使用掩码的所有可能的十六进制字符串列表的最有效方法

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

我有一个长度为32个字符的长字符串,其中包含用于屏蔽的字符“x”。生成具有特定长度并使用掩码的所有可能的十六进制字符串列表的最有效方法是什么。我们可以有多个字符掩码(多个 X) 例如:

如果我使用以下字符串作为程序的输入,

my_string = '0011223344x56677889xaabbccddee'

我希望将以下内容作为程序的输出(对输入字符串中的每个 x 从 0 迭代到 f):

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

您可以使用列表理解和 for 循环,如下所示:

my_string = '0011223344x56677889xaabbccddee'
hex_values = [0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f']
possible_outputs = [my_string]
for n in range(my_string.count('x')):
  tmp = [thestring.replace('x', str(hex), 1) for hex in hex_values for thestring in possible_outputs]
  possible_outputs.extend(tmp)

您可以将 itertools.combinations_with_replacement itertools.productre.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))

打印:

00112233440566778890aabbccddee
00112233440566778891aabbccddee
00112233440566778892aabbccddee
00112233440566778893aabbccddee
00112233440566778894aabbccddee
00112233440566778895aabbccddee
00112233440566778896aabbccddee

...

0011223344d56677889faabbccddee
0011223344e56677889eaabbccddee
0011223344e56677889faabbccddee
0011223344f56677889faabbccddee