In PHP, you have preg_replace($patterns, $replacements, $string), where you can make all your substitutions at once by passing in an array of patterns and replacements.
What is the equivalent in Python?
I noticed that the string and re functions replace() and sub() don’t take dictionaries…
Edited to clarify based on a comment by rick:
the idea is to have a dict with keys to be taken as regular expression patterns, such as '\d+S', and (hopefully) constant string values (hopefully w/o backreferences). Now editing my answer accordingly (i.e. to answer the actual question).
closest is probably:
for example:
with a
.getinstead of[]-indexing if you want to supply a default for matches that are missing inreplacements.Edit: what rick really wants is to have a dict with keys to be taken as regular expression patterns, such as
'\d+S', and (hopefully) constant string values (hopefully w/o backreferences). The cookbook recipe can be adapted for this purpose:Example use:
emits:
You could avoid building
lookupand just usemo.expand(d.values()[mo.lastindex-1]), but that might be a tad slow ifdis very large and there are many matches (sorry, haven’t precisely measured/benchmarked both approaches, so this is just a guess;-).