Python language: Custom-Syntax string template (template) detailed

Source: Internet
Author: User

String. Template () adds the substituted character, uses the "$" symbol, or within the string, uses "${}"; Use the String.substitute (dict) function when calling.

Can be inherited by "string." Template ", covering variable delimiter (delimiters) and Idpattern (alternate format), customizing different forms of templates.

Code:

#-*-Coding:utf-8-*-  
      
' 
Created 
     
on 2014.6.5 @author: Administrator 
     
@edition: Python 3.3.0, eclipse Pydev 
' '
      
      
      
import string  
      
template_text = ' ' 
    Delimiter:% 
    Replaced:%with_underscore 
    ingored:%notunderscored 
'
      
d = {' With_underscore ': ' Replaced ',  
     ' notunderscored ': ' Not replaced '}< C14/>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 (delimiter) is "%" and the replacement mode (Idpattern) must contain an underscore, so the 2nd is not replaced.

Author: csdn Blog spike_king

Back to the column page: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/extra/

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.