詳解Python中string模塊除去Str還剩下什么
string模塊可以追溯到早期版本的Python。以前在本模塊中實現的許多功能已經轉移到str物品。這個string模塊保留了幾個有用的常量和類來處理str物品。
字符串-文本常量和模板
目的:包含用于處理文本的常量和類。
功能
功能capwords()將字符串中的所有單詞大寫。字符串capwords.py
import strings = ’The quick brown fox jumped over the lazy dog.’print(s)print(string.capwords(s))
結果與調用split(),將結果列表中的單詞大寫,然后調用join()把結果結合起來。
$ python3 string_capwords.pyThe quick brown fox jumped over the lazy dog.The Quick Brown Fox Jumped Over The Lazy Dog.
模板
字符串模板作為PEP 292作為內建內插語法的替代。帶著string.Template內插,變量通過在名稱前加上(例如,(例如,(例如,var)?;蛘撸绻枰脑?,也可以用花括號(例如,${var}).此示例使用%運算符和新的格式字符串語法。str.format().
#字符串模板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))
在前兩種情況下,觸發器字符($或%)是通過重復兩次來逃脫的。對于格式語法,兩者都是{和}需要通過重復它們來逃脫。
$ python3 string_template.pyTEMPLATE:Variable : fooEscape : $Variable in text: fooiableINTERPOLATION:Variable : fooEscape : %Variable in text: fooiableFORMAT:Variable : fooEscape : {}Variable in text: fooiable
模板與字符串內插或格式化之間的一個關鍵區別是,參數的類型沒有被考慮在內。將值轉換為字符串,并將字符串插入到結果中。沒有可用的格式設置選項。例如,無法控制用于表示浮點值的數字數。
不過,有一個好處是,使用safe_substitute()方法可以避免異常,如果不是以參數形式提供模板所需的所有值。
#字符串模板丟失.pyimport stringvalues = {’var’: ’foo’}t = string.Template('$var is here but $missing is not provided')try: print(’substitute() :’, t.substitute(values))except KeyError as err: print(’ERROR:’, str(err))print(’safe_substitute():’, t.safe_substitute(values))
因為沒有價值missing在值字典中,KeyError是由substitute()。
而不是提高錯誤,safe_substitute()捕獲它并將變量表達式單獨保留在文本中。
$ python3 string_template_missing.pyERROR: ’missing’safe_substitute(): foo is here but $missing is not provided
高級模板
string.Template可以通過調整用于在模板正文中查找變量名稱的正則表達式模式來更改。一個簡單的方法是更改delimiter和idpattern類屬性。
#字符串模板import stringclass MyTemplate(string.Template): delimiter = ’%’ idpattern = ’[a-z]+_[a-z]+’template_text = ’’’ Delimiter : %% Replaced : %with_underscore Ignored : %notunderscored’’’d = { ’with_underscore’: ’replaced’, ’notunderscored’: ’not replaced’,}t = MyTemplate(template_text)print(’Modified ID pattern:’)print(t.safe_substitute(d))
在本例中,替換規則被更改,因此分隔符是%而不是$變量名必須包括中間的下劃線。
模式%notunderscored不會被任何東西替換,因為它不包含下劃線字符。
$ python3 string_template_advanced.pyModified ID pattern: Delimiter : % Replaced : replaced Ignored : %notunderscored
對于更復雜的更改,可以重寫pattern屬性并定義一個全新的正則表達式。
提供的模式必須包含四個命名組,用于捕獲轉義分隔符、命名變量、變量名的大括號版本和無效分隔符模式。
#字符串模板_defaultpattern.pyimport stringt = string.Template(’$var’)print(t.pattern.pattern)
價值t.pattern是已編譯的正則表達式,但原始字符串可通過其pattern屬性。
$(?: (?P<escaped>$) |# two delimiters (?P<named>[_a-z][_a-z0-9]*) | # identifier {(?P<braced>[_a-z][_a-z0-9]*)} | # braced identifier (?P<invalid>) # ill-formed delimiter exprs)
此示例定義一個新模式以創建一種新類型的模板,使用{{var}}作為變量語法。
#字符串模板_newsyntax.pyimport reimport stringclass MyTemplate(string.Template): delimiter = ’{{’ pattern = r’’’ {{(?: (?P<escaped>{{)| (?P<named>[_a-z][_a-z0-9]*)}}| (?P<braced>[_a-z][_a-z0-9]*)}}| (?P<invalid>) ) ’’’t = MyTemplate(’’’{{{{{{var}}’’’)print(’MATCHES:’, t.pattern.findall(t.template))print(’SUBSTITUTED:’, t.safe_substitute(var=’replacement’))
named和braced模式都必須單獨提供,即使它們是相同的。運行示例程序將生成以下輸出:
$ python3 string_template_newsyntax.pyMATCHES: [(’{{’, ’’, ’’, ’’), (’’, ’var’, ’’, ’’)]SUBSTITUTED:{{replacement
格式化程序
這個Formatter類實現與format()方法str。它的功能包括類型強制、對齊、屬性和字段引用、命名和位置模板參數以及特定于類型的格式選項。大多數時候format()方法是這些特性的更方便的接口,但是Formatter作為構建子類的一種方法,用于需要變體的情況下。
常數
這個string模塊包括一些與ASCII和數字字符集相關的常量。
#字符串常數.pyimport inspectimport stringdef is_str(value): return isinstance(value, str)for name, value in inspect.getmembers(string, is_str): if name.startswith(’_’): continue print(’%s=%rn’ % (name, value))
這些常量在處理ASCII數據時很有用,但是由于在某種形式的Unicode中遇到非ASCII文本越來越常見,因此它們的應用受到限制。
$ python3 string_constants.pyascii_letters=’abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’ascii_lowercase=’abcdefghijklmnopqrstuvwxyz’ascii_uppercase=’ABCDEFGHIJKLMNOPQRSTUVWXYZ’digits=’0123456789’hexdigits=’0123456789abcdefABCDEF’octdigits=’01234567’printable=’0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!'#$%&’()*+,-./:;<=>?@[]^_`{|}~ tnrx0bx0c’punctuation=’!'#$%&’()*+,-./:;<=>?@[]^_`{|}~’whitespace=’ tnrx0bx0c’
到此這篇關于詳解Python中string模塊除去Str還剩下什么的文章就介紹到這了,更多相關Python string模塊內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
