Sololearn: Learn to Code
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4
import re def multiple_replacements(i, x, mystring): rep = {re.escape(k):v for k,v in zip(i,x)} pattern = re.compile("|".join(rep.keys())) text = pattern.sub(lambda m: rep[re.escape(m.group(0))], mystring) return text print(multiple_replacements(("1","2","3"),("6","7","2"),"1 * 2 = 43")) # 6 * 7 = 42 Modified this code to work with Python 3. https://stackoverflow.com/a/6117124
24th Jul 2019, 1:54 PM
Diego
Diego - avatar
+ 6
If you can put the substitution pairs in a dictionary, then the approach described here may work: https://stackoverflow.com/questions/15175142/how-can-i-do-multiple-substitutions-using-regex-in-JUMP_LINK__&&__python__&&__JUMP_LINK Another idea is that in the sub(pattern, repl, string) function, the repl parameter can actually be a function and a match object is passed to it automatically. So you can write a function to make the correct replacement. You may also chain the sub function, something like: sub(x1, x2, sub(y1, y2, string)) https://code.sololearn.com/c4d5quRYe9op/?ref=app
24th Jul 2019, 1:16 PM
Tibor Santa
Tibor Santa - avatar
+ 3
[1-6]
13th Jul 2020, 3:58 AM
Ryan Wilke
Ryan Wilke - avatar
+ 1
re.sub(‘{}’.format(x2), x1) re.sub(‘{}’.format(y2), y1) This should work. Notice I removed the ‘r’ from the string. It’s not necessary because you aren’t using any metacharacters or backslashes here, and I’m not sure if string’s ‘.format()’ method works on raw strings. If I’m misunderstanding your question, please let me know.
24th Jul 2019, 11:35 AM
Rora
+ 1
def sub(pttrns, strings): for i, s in enumerate(strings): re.sub(‘{}’.format(pttrns[i]), s) like this? this will take 2 lists as args and will sub the string with the corresponding index
24th Jul 2019, 9:35 PM
Rora
+ 1
[1-6]
26th May 2021, 1:19 PM
Hayder Jawad Al-ATBEE
Hayder Jawad Al-ATBEE - avatar
0
This is how I have written it. Repeat the regex re.sub(re.sub())) twice within the regex to return different variable x2 and y2. newstr = re.sub(r'x1', 'x2', re.sub(r'y1', 'y2', str)) https://code.sololearn.com/c0FSk8ZFn8r3/?ref=app
2nd Apr 2021, 9:13 PM
Steve Nova
Steve Nova - avatar