Skip to content

Instantly share code, notes, and snippets.

@gwsu2008
Forked from carlsmith/replace.py
Created November 25, 2019 00:22
Show Gist options
  • Save gwsu2008/4d12288ef1214cd24a1d70e46a9a47d6 to your computer and use it in GitHub Desktop.
Save gwsu2008/4d12288ef1214cd24a1d70e46a9a47d6 to your computer and use it in GitHub Desktop.
A Python function that does multiple string replace ops in a single pass.
import re
def replace(string, substitutions):
substrings = sorted(substitutions, key=len, reverse=True)
regex = re.compile('|'.join(map(re.escape, substrings)))
return regex.sub(lambda match: substitutions[match.group(0)], string)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment