This article mainly introduces the relevant information of the string.py module in Python. The introduction in the article is very detailed and has certain reference value for everyone. Friends who need it can take a look below.
1. Usage
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
abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 0123456789abcdefABCDEF 01234567 !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,- ./:;<=>?@[\]^_`{|}~
## 2. Template class:
format() method of string objects, which can help better understanding. First, create a new python file:
string_template.py,
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, enter in the python command line:
$ python string_template.py
Result
TEMPLATE: Variable : foo Escape : $ Variable in text: fooiable INTERPOLATION: Variable : foo Escape : % Variable in text: fooiable FORMAT: Variable : foo Escape : {}
Such as string_template_advanced.py example:
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))
Result
$ python string_template_advanced.py Modified ID pattern: Delimiter : % Replaced : replaced Igonred : %notunderscored
The above is the detailed content of Module string.py in Python. For more information, please follow other related articles on the PHP Chinese website!