Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 620
Jilong Yin Avatar asked Oct 05 '21 13:10

Jilong Yin


People also ask

How do you replace two substrings in Python?

The below example uses replace() function provided by Python Strings. It replaces all the occurrences of a sub-string to a new string by passing the old and new strings as parameters to the replace() function. Multiple calls to replace() function are required to replace multiple substrings in a string.

How do you replace all occurrences of substring in a string?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag. replaceAll() method is more straight forward.

How do you replace multiple values?

Find and replace multiple values with nested SUBSTITUTE The easiest way to find and replace multiple entries in Excel is by using the SUBSTITUTE function. The formula's logic is very simple: you write a few individual functions to replace an old value with a new one.


1 Answers

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'
like image 165
I'mahdi Avatar answered Oct 14 '22 07:10

I'mahdi