Created
June 23, 2019 10:00
-
-
Save ahmed4end/b73237e42d3aa47cce9e140e5d2c4123 to your computer and use it in GitHub Desktop.
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 | |
#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