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 re.sub():

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.

  • re.sub can take a function in place of a replacement string - the conditional logic around replacement could go into this function.... – iruvar Mar 15 at 18:12
  • @iruvar, then you could have something like re.sub("hello|this", func, s) and in func check which word was matched, right? That doesn't sound very straightforward either... :) – ilkkachu Mar 15 at 22:38
  • ikkachu, if you convert replacements into a dict ({"hello": "hi", "this": "it's"} ), the function boils down to def func(matchobj): return replacements.get(matchobj.group(), "") - pretty straightforward – iruvar Mar 16 at 22:20
  • @iruvar, in that sense, yes. Though the matching pattern would still need to be a combination of all the patterns to be replaced, right? But anyway, that's starting to sound like an independent answer... – ilkkachu Mar 16 at 22:27
  • True. But that's easily accomplished via a '|'.join(replacements). Given that this is not a programming SE site I'm unsure if a separate answer is warranted so I leave it here for the record as a comment – iruvar Mar 17 at 1:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.