Search code examples
pythonsubstring

How to replace multiple substrings at the same time


I have a string like

a = "X1+X2*X3*X1"
b = {"X1":"XX0","X2":"XX1","X0":"XX2"}

I want to replace the substring 'X1,X2,X3' using dict b.

However, when I replace using the below code,

for x in b:
    a = a.replace(x,b[x])
print(a)

'XXX2+XX1*X3'

Expected result is XX0 + XX1*X3*XX0

I know it is because the substring is replaced in a loop, but I don't know how to solve it.


Solution

  • You can create a pattern with '|' then search in dictionary transform like below.

    Try this:

    import re
    a = "X1+X2*X3*X1"
    b = {"X1":"XX0","X2":"XX1","X0":"XX2"}
    
    pattern = re.compile("|".join(b.keys()))
    out = pattern.sub(lambda x: b[re.escape(x.group(0))], a)
    

    Output:

    >>> out
    'XX0+XX1*X3*XX0'