Skip to content

Instantly share code, notes, and snippets.

@malexandre
Created July 2, 2015 14:32
Show Gist options
  • Save malexandre/8379c68ed4ea92ed465a to your computer and use it in GitHub Desktop.
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
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