標籤: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模組