Created
April 5, 2011 20:31
-
-
Save sspencer/904478 to your computer and use it in GitHub Desktop.
Simple template replacement function
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 | |
def make_replacer(d): | |
"bind dictionary to replacement function" | |
return lambda m: d.get(m.group(1), m.group(0)) | |
def subs(template, obj): | |
"substitute values from obj into ${vars} in template" | |
repl = make_replacer(obj) | |
return re.sub("""\$\{(\w+)\}""", repl, template) | |
# to use: | |
if __name__ == "__main__": | |
subs("Say ${greeting} to ${place}", {"greeting": "HELLO", "place": "WORLD"}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment