Can I use regex in python to have multiple types of substitutions? Like in this string "hello, this is me" I want to replace 'hello' with 'hi' and 'this' with 'its'. Can I do it in a single line? Or can I use back-referencing in regex for it?
No, not really, since you need to call
re.sub() and give the string to it as an argument. You'd get ugly nested calls. Instead,
str.replace() works as method on the string itself and returns the new string, so you can chain the calls:
s='hello, this is me' s=s.replace("hello", "hi").replace("this", "it's")
But if you have a list of replacements, you can of course loop over them even with
import re s='hello, this is me' replacements=[("hello", "hi"), ("this", "it's")] for pat,repl in replacements: s = re.sub(pat, repl, s)
And no, regexes by themselves don't really lend to multiple replacements.