Friday, May 6, 2011

How to use string's Template

Templates provide simple string substitutions mechanism, here's a simple demonstration:
from string import Template

template = Template('The president of $state is $name')
message = template.substitute(state='USA', name='Obama')
print '1.',message
message = template.substitute(state='France', name='Sarkozy')
print '2.',message

 # will raise an exception
 message = template.substitute(state='England')
except Exception as e:
 print 'I cannot fill the placeholder',e
 #  original name placeholder will be used
 message = template.safe_substitute(state='England') 

print '3.',message
The output of this script will be
1. The president of USA is Obama
2. The president of France is Sarkozy
I cannot fill the placeholder 'name'
3. The president of England is $name

No comments:

Post a Comment