Skip to content

Instantly share code, notes, and snippets.

@sspencer
Created April 5, 2011 20:31
Show Gist options
  • Save sspencer/904478 to your computer and use it in GitHub Desktop.
Save sspencer/904478 to your computer and use it in GitHub Desktop.
Simple template replacement function
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