-
-
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.
This file contains hidden or 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