Skip to content

Instantly share code, notes, and snippets.

@pykong
Last active October 10, 2016 21:37
Show Gist options
  • Save pykong/df645e04c97ab7290653b9ed05d68fd1 to your computer and use it in GitHub Desktop.
Save pykong/df645e04c97ab7290653b9ed05d68fd1 to your computer and use it in GitHub Desktop.
Substitute multiple patterns in string with those in a provided dictionary.
import re
def multisub(dict, text):
# Create a regular expression from the dictionary keys
regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
# For each match, look-up corresponding value in dictionary
return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment