This article introduces the Python module string. py. This article describes the usage of the Python module string. py.
String constant:
Import string
Print (string. ascii_lowercase)
Print (string. ascii_uppercase)
Print (string. ascii_letters)
Print (string. digits)
Print (string. hexdigits)
Print (string. octdigits)
Print (string. punctuation)
Print (string. printable)
Result
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890123456789abcdefABCDEF01234567!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,- ./:;<=>?@[\]^_`{|}~
1. Template class:
In fact, the Template class can be compared with the format () method of the formatted string and the String object to help you better understand. First, create a python file: string_template.py,
Then write the following content in it:
import stringvalues = {'var': 'foo'}t = string.Template("""Variable : $varEscape : $$Variable in text: ${var}iable""")print('TEMPLATE:', t.substitute(values))s = """Variable : %(var)sEscape : %%Variable in text: %(var)siable"""print('INTERPOLATION:', s % values)s = """Variable : {var}Escape : {{}}Variable in text: {var}iable"""print('FORMAT:', s.format(**values))
Then, enter the following in the python command line:
$ python string_template.py
Result
TEMPLATE:Variable : fooEscape : $Variable in text: fooiableINTERPOLATION:Variable : fooEscape : %Variable in text: fooiableFORMAT:Variable : fooEscape : {}
You can see that all three of them can be used to format strings. Only the modifiers of the three are different. A good thing about the Template class is that it can inherit the class, customize its modifier after instantiation, and define the variable name format as a regular expression. For example, string_template_advanced.py:
import string
class MyTemplate(string.Template): delimiter = '%' idpattern = '[a-z]+_[a-z]+'template_text = ''' Delimiter : %% Replaced : %with_underscore Igonred : %notunderscored'''d = { 'with_underscore': 'replaced', 'notunderscored': 'not replaced',}t = MyTemplate(template_text)print('Modified ID pattern:')print(t.safe_substitute(d))
First, explain the python file above. It defines a class MyTemplate, inherits the string Template class, and then reloads its two fields: Delimiter is the modifier and is now specified as '% ', instead of the previous '$ '. Then, idpattern specifies the variable format.
Result
$ python string_template_advanced.pyModified ID pattern: Delimiter : % Replaced : replaced Igonred : %notunderscored
Why is notunderscored not replaced? The reason is that the underscore '_' is specified in idpattern during class definition, and the variable name is not underlined, so it cannot be replaced.
The above is the detailed description of the string. py in the Python module. For more information, see other related articles in the first PHP community!