Reputation: 3
How would I take a string and replace all occurrences of a given character with all possible combinations of a list of characters?
e.g. string = "GPxLEKxLExx", replace x with ['A','B','C','D','E','F']
Such that it returns:
GPALEKALEAA GPBLEKALEAA GPBLEKBLEAA ... GPFLEKALEAA ... GPFLEKFLEFF
and all other combinations of these characters.
Based on one of the answers below, this is what worked for me:
from itertools import product
input_str = 'GPxLEKxLExx'
input_str = input_str.replace('x', '{}')
outputs = []
for comb in product('ABCDEF', repeat=4):
outputs.append(input_str.format(*comb))
Upvotes: 0
Views: 283
Reputation: 421
from itertools import combinations_with_replacement
input_str = 'GPxLEKxLExx'
input_str = input_str.replace('x', '{}')
outputs = []
for comb in combinations_with_replacement(['A','B','C','D','E','F'], 4):
outputs.append(input_str.format(*comb))
Edit: As @Phossel pointed out, the proper function was itertools.product
instead of combinations_with_replacement
. So for clarity, the fixed version is:
from itertools import product
input_str = 'GPxLEKxLExx'
input_str = input_str.replace('x', '{}')
outputs = []
for comb in product(['A','B','C','D','E','F'], repeat=4):
outputs.append(input_str.format(*comb))
Upvotes: 1
Reputation: 362
myString = "GPxLEKxLExx"
charList = [ 'A', 'B', 'C', 'D', 'E', 'F']
newList = []
for i in charList:
newList.append(myString.replace("x",i))
The value in the newList is the correct answer
Upvotes: 0
Reputation:
You can do this
from itertools import combinations
string = "GP{}LEK{}LE{}{}"
l= ['A','B','C','D','E','F']
l2=list(combinations(l, 4))
for i in l2:
print(string.format(*i))
Upvotes: 0