Python標準庫--string模組

來源:互聯網
上載者:User

標籤:ext   windows   style   標準   異常   this   val   ascii   var   

string中包含了處理文本的常量和模板

常量

print(string.whitespace)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)"""     abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890123456789abcdefABCDEF01234567!"#$%&‘()*+,-./:;<=>[email protected][\]^_`{|}~0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&‘()*+,-./:;<=>[email protected][\]^_`{|}~     """# 第一個是幾個空行,Windows輸出有點問題

函數

capwords():每個單字首大寫,可自訂單詞間分隔字元
s = ‘This is a dog‘print(s)print(string.capwords(s))s2 = ‘This-is-a-dog‘print(s2)print(string.capwords(s2, ‘-‘))"""This is a dogThis Is A DogThis-is-a-dogThis-Is-A-Dog"""

模板

substitute() 傳入模板變數, 沒有就報錯
safe_substitute() 捕獲異常,原樣輸出
 
values = {‘var‘: ‘boo‘}t = string.Template("""    Variable        :$var    Excape          : $$    Variable in text: ${var}iable""")print(t.substitute(values))t2 = string.Template("$var is here but $missing is not provided")try:    print(t2.substitute(values))except KeyError as err:    print(‘ERROR:‘, str(err))print(t2.safe_substitute(values))"""    Variable        :boo    Excape          : $    Variable in text: booiableERROR: ‘missing‘boo is here but $missing is not provided"""

$$ 輸出 $

自訂模板類繼承string中的模板類,可自訂變數定界符,和變數尋找規則

class MyTemplate(string.Template):    delimiter = ‘%‘    idpattern = ‘[a-z]+_[a-z]+‘

Formatter

 

Python標準庫--string模組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.