Skip to content

Instantly share code, notes, and snippets.

@ahmed4end
Created June 23, 2019 10:00
Show Gist options
  • Save ahmed4end/b73237e42d3aa47cce9e140e5d2c4123 to your computer and use it in GitHub Desktop.
Save ahmed4end/b73237e42d3aa47cce9e140e5d2c4123 to your computer and use it in GitHub Desktop.
import re
#the extended version
def multiple_replace(dict, text):
# Create a regular expression from the dictionary keys
regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
# For each match, look-up corresponding value in dictionary
return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
#the short version
multi_replace = lambda dict, text: re.sub(r"|".join(map(re.escape, dict.keys())), lambda m: dict[m.string[m.start():m.end()]], text)
print(multi_replace({"ahmed":"no one", "good":"good enough."}, "ahmed is good"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment