Python 模块之 string.py
用法
字符串常量:
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)
結果
abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 0123456789abcdefABCDEF 01234567 !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~其實,Template類,可以和格式化字符串的用法還有字符串對象的format()方法做對比,可以幫助更好地理解。首先,新建一個python文件:string_template.py,
然后在里面寫入以下內容:
然后,在python命令行中輸入:
$ python string_template.py結果
TEMPLATE: Variable : foo Escape : $ Variable in text: fooiableINTERPOLATION: Variable : foo Escape : % Variable in text: fooiableFORMAT: Variable : foo Escape : {}可以看到三者之間都可以起到對字符串里進行格式化的效果。只是三者的修飾符不一樣。Template類好的一點就是其可以通過繼承類,實例化后自定義其修飾符,并且也可以對變量的名字格式進行正則表達式的定義。如string_template_advanced.py示例:
import string class MyTemplate(string.Template):delimiter = '%'idpattern = '[a-z]+_[a-z]+'template_text = '''Delimiter : %%Replaced : %with_underscoreIgonred : %notunderscored '''d = {'with_underscore': 'replaced','notunderscored': 'not replaced', }t = MyTemplate(template_text) print('Modified ID pattern:') print(t.safe_substitute(d))首先,解釋下上面python文件。里面定義了一個類MyTemplate,繼承了string的Template類,然后,對其兩個域進行重載: Delimiter為修飾符,現在指定為了‘%’,而不是之前的‘$’。 接著,idpattern是對變量的格式指定。
結果
$ python string_template_advanced.py Modified ID pattern:Delimiter : %Replaced : replacedIgonred : %notunderscored為什么notunderscored沒有被替換呢?原因是我們在類定義的時候,idpattern里指定要出現下劃線'_', 而該變量名并沒有下劃線,故替代不了。
轉載于:https://www.cnblogs.com/brad1994/p/6536676.html
總結
以上是生活随笔為你收集整理的Python 模块之 string.py的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HWSD全球土壤数据下载
- 下一篇: [Pro*c]滚动游标变量的使用