Home > Software design >  Replace particular character in a python string with multiple character and produce two different ou
Replace particular character in a python string with multiple character and produce two different ou

Time:06-15

Use case 1 :

str = '?0?'   #str is input string , we need to replace every '?' with [0,1].

so the resulting output will be :

['000','100','001','101']

use case 2 :

str = '?0' #input

Expected output :

['00','10']

use case 3 :

str='?'

Expected output :

['0','1']

The length of the string and number of '?' in string may vary for different inputs.

CodePudding user response:

Here's a solution using itertools.product to produce all possible products of [0,1] for a ? or the digit itself:

str = '?0?'
[''.join(p) for p in itertools.product(*[['0', '1'] if c == '?' else c for c in str])]

Output:

['000', '001', '100', '101']

CodePudding user response:

Without itertools:

s = '?0?'

a = ['']
for c in s:
    a = [b d for b in a for d in c.replace('?', '01')]

print(a)

Try it online!

  • Related