I am attempting to generate all combinations of special characters and numbers around a string. For example, suppose the string is 'notebook' and the special characters are @, #, $, %, & and numbers 0-9. This could generate: $#notebook12, notebook8, @5notebook0&. I am assuming no repeats of characters.
Thanks in advance.
So far I can only generate:
special = ['@','#','$','%','&',' ',0,1,2,3,4,5,6,7,8,9,' ']
choice = list(permutations(special, 2))
word = ['notebook']
pw_choice = word + choice
test = list(permutations(pw_choice, 2))
print(test)
But this results in a list of list that I would have to manipulate further. Is there an easier work around to produce the set of _ _ notebook _ _ ?
Try this:
from itertools import combinations, permutations
result = [
''.join(p)
for n_chars in range(len(special) + 1)
for chars in combinations(special, n_chars)
for p in permutations(('notebook',) + chars)
]
Example with special = ['@','#','$']
:
['notebook', 'notebook@', '@notebook', 'notebook#', '#notebook',
'notebook$', '$notebook', 'notebook@#', 'notebook#@',
'@notebook#', '@#notebook', '#notebook@', '#@notebook',
'notebook@$', 'notebook$@', '@notebook$', '@$notebook',
'$notebook@', '$@notebook', 'notebook#$', 'notebook$#',
'#notebook$', '#$notebook', '$notebook#', '$#notebook',
'notebook@#$', 'notebook@$#', 'notebook#@$', 'notebook#$@',
'notebook$@#', 'notebook$#@', '@notebook#$', '@notebook$#',
'@#notebook$', '@#$notebook', '@$notebook#', '@$#notebook',
'#notebook@$', '#notebook$@', '#@notebook$', '#@$notebook',
'#$notebook@', '#$@notebook', '$notebook@#', '$notebook#@',
'$@notebook#', '$@#notebook', '$#notebook@', '$#@notebook']
If you only want at most two chars before and after the "notebook" string:
from itertools import combinations
result = [
f'{"{}"*b}notebook{"{}"*a}'.format(*c)
for b in range(3)
for a in range(3)
for c in combinations(special, a + b)
]
This is the result (with special = ['@','#','$']
):
['notebook', 'notebook@', 'notebook#', 'notebook$', 'notebook@#',
'notebook@$', 'notebook#$', '@notebook', '#notebook', '$notebook',
'@notebook#', '@notebook$', '#notebook$', '@notebook#$',
'@#notebook', '@$notebook', '#$notebook', '@#notebook$']