Python中的模組string.py

來源:互聯網
上載者:User
這篇文章主要介紹了Python中模組之string.py的相關資料,文中介紹的非常詳細,對大傢具有一定的參考價值,需要的朋友們下面來一起看看吧。

一、用法

字串常量:

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)

結果

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890123456789abcdefABCDEF01234567!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,- ./:;<=>?@[\]^_`{|}~

二、Template類:

其實,Template類,可以和格式化字串的用法還有字串對象的format()方法做對比,可以協助更好地理解。首先,建立一個python檔案:string_template.py,

然後在裡面寫入以下內容:

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))

然後,在python命令列中輸入:

$ python string_template.py

結果

TEMPLATE:Variable : fooEscape  : $Variable in text: fooiableINTERPOLATION:Variable : fooEscape  : %Variable in text: fooiableFORMAT:Variable : fooEscape  : {}

可以看到三者之間都可以起到對字串裡進行格式化的效果。只是三者的修飾符不一樣。Template類好的一點就是其可以通過繼承類,執行個體化後自訂其修飾符,並且也可以對變數的名字格式進行Regex的定義。

如string_template_advanced.py樣本:

import stringclass 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))

首先,解釋下上面python檔案。裡面定義了一個類MyTemplate,繼承了string的Template類,然後,對其兩個域進行重載: Delimiter為修飾符,現在指定為了‘%',而不是之前的‘$'。 接著,idpattern是對變數的格式指定。

結果

$ python string_template_advanced.pyModified ID pattern: Delimiter : % Replaced : replaced Igonred : %notunderscored

為什麼notunderscored沒有被替換呢?原因是我們在類定義的時候,idpattern裡指定要出現底線'_', 而該變數名並沒有底線,故替代不了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.