Created
July 2, 2015 14:32
-
-
Save malexandre/8379c68ed4ea92ed465a to your computer and use it in GitHub Desktop.
Use a dict to replace a group of text in a string in python
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 | |
s = "string to replace with KEY1 and KEY2, but also KEY3. But KEY5 is not defined in the replacements dict." | |
pattern = re.compile(r'\b(' + '|'.join(replacements.keys()) + r')\b') | |
replacements = { | |
'KEY': 'VALUE', | |
'KEY2': 'VALUE2', | |
'KEY3': 'VALUE3', | |
'KEY4': 'VALUE4' | |
} | |
print pattern.sub(lambda x: replacements[x.group()], s) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment