Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

224
Views
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.

over 4 years ago · Santiago Trujillo
4 answers
Answer question

0

You can use the repl parameter of re.sub:

import re
re.sub('X\d', lambda x: b.get(x.group(), x.group()), a)

output:

'XX0+XX1*X3*XX0'
over 4 years ago · Santiago Trujillo Report

0

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'
over 4 years ago · Santiago Trujillo Report

0

The reason for this is beacuse you are replacing the same string multiple times, so behind the scenes (or between the iterations) there are a few more switches in the middle that you probably don't see (unless debugging this code). Please note that dictionary keys are not ordered, so you cannot assume what's replaced when. I suggest you use template

over 4 years ago · Santiago Trujillo Report

0

With just built-in functions. The given b dictionary contains cycles between keys and values, so used the f-string notation to perform the substitutions. To escape the {} one should double them {{}}, used for repeated substitution. The enumerate is needed to get unique keys in the new dictionary, so no more cycles.

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

new_dict = {}
for i, k in enumerate(b):
    sub_format =  f'{k}' + f'{i}'
    new_dict[sub_format] = b[k]
    a = a.replace(k, f'{{{sub_format}}}')

print(a.format(**new_dict))

Output

XX0+XX1*X3*XX0
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!