Template-type string Template usage in the string Module of Python

Source: Internet
Author: User
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!  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.