Using string. Template, we can customize the string replacement standard for Python. here we will use the example to parse the Template-type string Template usage in the string Module of Python:
String. Template ()
Add replacement characters in string. Template (), use the "$" symbol, or use the "$ {}" character in the string. use the string. substitute (dict) function for calling.
You can inherit "string. Template", override the variables delimiter (delimiter) and idpattern (replacement format), and customize templates of different forms.
Code:
# -*- coding: utf-8 -*- import string template_text = ''''' Delimiter : %% Replaced : %with_underscore Ingored : %notunderscored ''' d = {'with_underscore' : 'replaced', 'notunderscored' : 'not replaced'} class MyTemplate(string.Template): delimiter = '%' idpattern = '[a-z]+_[a-z]+' t = MyTemplate(template_text) print('Modified ID pattern: ') print(t.safe_substitute(d))
Output:
Modified ID pattern: Delimiter : % Replaced : replaced Ingored : %notunderscored
Note: The delimiter is "%", and the replacement mode (idpattern) must contain underscores, So 2nd are not replaced.
Regular expression replacement
The pattern of string. Template is a regular expression. you can overwrite the pattern attribute to define a new regular expression.
For example, use the new separator "{" and use {var} as the variable syntax.
Code:
import string t = string.Template('$var') print(t.pattern.pattern) class MyTemplate(string.Template): delimiter = '{{' pattern = r''''' \{\{(?: (?P
\{\{) | # Escape sequence of two delimiters (?P
[_a-z][_a-z0-9]*)\}\} | # delimiter and a Python identifier {(?P
[_a-z][_a-z0-9]*)}\}\} | # delimiter and a braced identifier (?P
) # Other ill-formed delimiter exprs ) ''' t2 = MyTemplate(''''' {{{{ {{var}} ''') print('MATCHES: ', t2.pattern.findall(t2.template)) print('SUBSTITUTED: ', t2.safe_substitute(var='replacement'))
Output:
\$(?: (?P
\$) | # Escape sequence of two delimiters (?P
[_a-z][_a-z0-9]*) | # delimiter and a Python identifier {(?P
[_a-z][_a-z0-9]*)} | # delimiter and a braced identifier (?P
) # Other ill-formed delimiter exprs ) MATCHES: [('{{', '', '', ''), ('', 'var', '', '')] SUBSTITUTED: {{ replacement
Secure replacement of string templates (safe_substitute)
String Template (sting. Template). when replaced, use substitute (). If you fail to provide all the parameter values required by the Template, an exception occurs.
If you use safe_substitute (), that is, secure replacement, the existing dictionary value is replaced and the existing replacement symbols are retained.
Code:
import string values = {'var' : 'foo'} t = string.Template('''''$var is here but $ missing is not provided! ''') try: print 'substitute() : ', t.substitute(values) except ValueError as err: print 'Error:', str(err) print 'safe_substitude() : ', t.safe_substitute(values)
Output:
substitute() : Error: Invalid placeholder in string: line 1, col 18 safe_substitude() : foo is here but $ missing is not provided!