python: String template replacement

capwords function

Capitalize each word in the sequence

def capwords(s, sep=None):
    """capwords(s [,sep]) -> string

    Split the argument into words using split, capitalize each
    word using capitalize, and join the capitalized words using
    join.  If the optional second argument sep is absent or None,
    runs of whitespace characters are replaced by a single space
    and leading and trailing whitespace are removed, otherwise
    sep is used to split and join the words.

    """
    return (sep or ' ').join(x.capitalize() for x in s.split(sep))

From the source code, we can see at the return that we first use split to cut (the default is to cut with spaces), and then use join to merge the results

Chestnuts:

import string


s = 'this is old old man'
print(s)

print(string.capwords(s))

The results after operation are as follows

this is old old man
This Is Old Old Man

Process finished with exit code 0

From the running results, we can clearly see that the original lowercase words have finally become capitalized

 

Template

Template splicing is also an alternative to built-in splicing, using string When splicing template, prefix the name with $to identify the variable (for example: $var). If you want to distinguish it from the surrounding variables, add a curly bracket (for example: ${var}).

Chestnuts:

import string


values = {'var': 66}


t = string.Template("""
variable :   $var
escape  :   $var
variable in text    :   ${var}Splice with me
""")
print(t.substitute(values))
print(t.safe_substitute(values))

The results after operation are as follows

variable :   66
escape  :   66
variable in text    :   66 Splice with me


variable :   66
escape  :   66
variable in text    :   66 Splice with me

From the above results, the data has been replaced successfully. The only bad thing is that the data is character type. If the parameter type needs to be replaced, another layer of processing must be done You can do it yourself

 

substitute and safe_substitute method

  1. When substituting, replace if it exists, and throw KeyError if it does not exist

  2. safe_ When substituting, replace if it exists. If it does not exist, the original parameter will be returned and no error will be thrown

Chestnut: substitute method

import string

values = {'var': 66}


t = string.Template("""
variable :  $var
escape  :   $var
missing :   $missing
variable in text    :   ${var}Splice with me
""")
print(t.substitute(values))

The results after operation are as follows

Traceback (most recent call last):
  File "/Users/lifeng/python-projects/Test/pythonScripts/python_string.py", line 21, in <module>
    print(t.substitute(values))
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/string.py", line 121, in substitute
    return self.pattern.sub(convert, self.template)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/string.py", line 114, in convert
    return str(mapping[named])
KeyError: 'missing'

It can be seen from the above operation results that the error is KeyError: 'missing'

 

Chestnut: safe_substitute method

import string

values = {'var': 66}


t = string.Template("""
variable :  $var
escape  :   $var
missing :   $missing
variable in text    :   ${var}Splice with me
""")
print(t.safe_substitute(values))

The results after operation are as follows

variable :  66
escape  :   66
missing :   $missing
variable in text    :   66 Splice with me


Process finished with exit code 0

From the above operation results, if there is no parameter replacement, the original parameter will be returned without error

 

 

Maybe sometimes we feel uncomfortable with the $symbol and want to replace it with another symbol, so we can inherit the Template and rewrite it

class MyTemplate(string.Template):
    delimiter = '!'


l = MyTemplate("""
variable :  !var
escape  :   !var
missing :   $missing
variable in text    :   ${var}Splice with me
""")
print(l.substitute(values))

In the above code, we just modify the value of the delimiter variable in the source code. The results after running are as follows

In the above code, we modified the delimiter $symbol to! Symbol and parameter replacement are also successful. Of course, you can rewrite other codes if you want, because the Template class itself has regular expressions. As long as the source code can understand it, change it

 

 

The above summary may or may not help you, but I hope it can help you. In case of doubt and ambiguity, the comments in the comment area will be corrected and released in time. Thank you!

 

 

Unfinished, to be continued

I've been working hard. I hope you too

 

WeChat search official account: use python

 

 

Keywords: Python template

Added by jeff8j on Fri, 18 Feb 2022 17:44:55 +0200