-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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