Skip to content

Instantly share code, notes, and snippets.

@iamharbie
Forked from bgusach/multireplace.py
Created June 5, 2019 12:27
Show Gist options
  • Save iamharbie/654c20721ec60fc9b67db6e4b1773e84 to your computer and use it in GitHub Desktop.
Save iamharbie/654c20721ec60fc9b67db6e4b1773e84 to your computer and use it in GitHub Desktop.
Python string multireplacement
def multireplace(string, replacements):
"""
Given a string and a replacement map, it returns the replaced string.
:param str string: string to execute replacements on
:param dict replacements: replacement dictionary {value to find: value to replace}
:rtype: str
"""
# Place longer ones first to keep shorter substrings from matching where the longer ones should take place
# For instance given the replacements {'ab': 'AB', 'abc': 'ABC'} against the string 'hey abc', it should produce
# 'hey ABC' and not 'hey ABc'
substrs = sorted(replacements, key=len, reverse=True)
# Create a big OR regex that matches any of the substrings to replace
regexp = re.compile('|'.join(map(re.escape, substrs)))
# For each match, look up the new string in the replacements
return regexp.sub(lambda match: replacements[match.group(0)], string)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment