sudarsan
sudarsan

Reputation: 41

Replace particular character in a python string with multiple character and produce two different outputs

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.

Upvotes: 0

Views: 42

Answers (2)

Kelly Bundy
Kelly Bundy

Reputation: 27629

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!

Upvotes: 0

Nick
Nick

Reputation: 147206

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']

Upvotes: 1

Related Questions