Python module string.py details
- 2020-05-27 05:56:07
- OfStack
Use 1.
String constants:
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)
The results of
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
0123456789abcdefABCDEF
01234567
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-
./:;<=>?@[\]^_`{|}~
2. Template class:
Actually, the Template class can be used for formatting strings as well as string objects
format()
Comparing methods can help you understand better. First, create a new python file:
string_template.py
,
Then write the following:
import string
values = {'var': 'foo'}
t = string.Template("""
Variable : $var
Escape : $$
Variable in text: ${var}iable
""")
print('TEMPLATE:', t.substitute(values))
s = """
Variable : %(var)s
Escape : %%
Variable in text: %(var)siable
"""
print('INTERPOLATION:', s % values)
s = """
Variable : {var}
Escape : {{}}
Variable in text: {var}iable
"""
print('FORMAT:', s.format(**values))
Then, on the python command line, type:
$ python string_template.py
The results of
TEMPLATE:
Variable : foo
Escape : $
Variable in text: fooiable
INTERPOLATION:
Variable : foo
Escape : %
Variable in text: fooiable
FORMAT:
Variable : foo
Escape : {}
You can see that all three of them have the effect of formatting the string. Only the three have different modifiers. One good thing about the Template class is that it can inherit from the class, instantiate and customize its modifiers, and it can also define regular expressions for the name format of variables.
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, which inherits Template from string, and then overloads its two fields: Delimiter is the modifier, now specified as' %' instead of the previous' $'. Next, idpattern specifies the format of the variable.
The results of
$ python string_template_advanced.py
Modified ID pattern:
Delimiter : %
Replaced : replaced
Igonred : %notunderscored
Why hasn't notunderscored been replaced? The reason is that when we defined the class, idpattern specified that the underscore '_' should appear, but the variable name is not underlined, so it cannot be replaced.
conclusion