+ 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
+ 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
+ 3
[1-6]
+ 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.
+ 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
+ 1
[1-6]
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