Skip to content

Instantly share code, notes, and snippets.

@alterEgo123
Forked from carlsmith/replace.py
Created March 11, 2020 07:16
Show Gist options
  • Save alterEgo123/ff2a5030f6fc9a6d9d8ae3f4c5bfe7b8 to your computer and use it in GitHub Desktop.
Save alterEgo123/ff2a5030f6fc9a6d9d8ae3f4c5bfe7b8 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