This article mainly introduces the string.py of the module in Python, the relevant information, the article introduced in very detailed, for everyone has a certain reference value, the need for friends below to see it together.
First, usage
String constants:
Import Stringprint (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)
Results
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890123456 789abcdefabcdef01234567! " #$%& ' () *+,-./:;<=>?@[\]^_ ' {|} ~0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz! " #$%& ' () *+,-./:;<=>?@[\]^_ ' {|} ~
Second, template class:
In fact, the template class, can be compared with the use of formatted strings and the method of String objects format()
, can help to better understand. First, create a new Python file: string_template.py
,
Then write the following in the text:
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, on the Python command line, enter:
$ python string_template.py
Results
TEMPLATE:Variable:fooEscape : $Variable in Text:fooiableINTERPOLATION:Variable:fooEscape :%variable in text : FooiableFORMAT:Variable:fooEscape : {}
You can see that all three can play a formatting effect on a string. Only the modifier of the three is different. The good thing about the template class is that it can be instantiated by inheriting the class, customizing its modifiers, and also defining a regular expression for the name format of the variable.
As string_template_advanced.py example:
Import Stringclass MyTemplate (string. Template): delimiter = '% ' Idpattern = ' [a-z]+_[a-z]+ ' template_text = ' ' delimiter: percent replaced:%with_underscore Igonr Ed:%notunderscored ' d = {' With_underscore ': ' Replaced ', ' notunderscored ': ' Not replaced ',}t = MyTemplate (Template_tex T) print (' Modified ID pattern: ') print (T.safe_substitute (d))
First, explain the above Python file. It defines a class MyTemplate, inherits the template class of string, and then overloads its two fields: delimiter is the modifier and is now specified for '% ' instead of the previous ' $ '. Next, Idpattern is the format of the variable specified.
Results
$ python string_template_advanced.pymodified ID pattern:delimiter:% replaced:replaced igonred:%notunderscored
Why is notunderscored not replaced? The reason is that when we define the class, we specify the underscore ' _ ' in Idpattern, and the variable name is not underlined, so it cannot be replaced.