詳解Python中string模塊除去Str還剩下什么
string模塊可以追溯到早期版本的Python。
以前在本模塊中實現(xiàn)的許多功能已經(jīng)轉(zhuǎn)移到str物品。
這個string模塊保留了幾個有用的常量和類來處理str物品。
字符串-文本常量和模板
目的:包含用于處理文本的常量和類。
功能
功能capwords()將字符串中的所有單詞大寫。
字符串capwords.py
import string s = 'The quick brown fox jumped over the lazy dog.' print(s) print(string.capwords(s))
結(jié)果與調(diào)用split(),將結(jié)果列表中的單詞大寫,然后調(diào)用join()把結(jié)果結(jié)合起來。
$ python3 string_capwords.py The quick brown fox jumped over the lazy dog. The Quick Brown Fox Jumped Over The Lazy Dog.
模板
字符串模板作為PEP 292作為內(nèi)建內(nèi)插語法的替代。帶著string.Template內(nèi)插,變量通過在名稱前加上(例如,(例如,(例如,var)?;蛘?,如果需要的話,也可以用花括號(例如,${var}).
此示例使用%運算符和新的格式字符串語法。str.format().
#字符串模板 import string values = {'var': 'foo'} t = string.Template(""" Variable : $var Escape : $$ Variable in text: ${var}iable """) print('TEMPLATE:', t.substitute(values)) s = """ Variable : %(var)s Escape : %% Variable in text: %(var)siable """ print('INTERPOLATION:', s % values) s = """ Variable : {var} Escape : {{}} Variable in text: {var}iable """ print('FORMAT:', s.format(**values))
在前兩種情況下,觸發(fā)器字符($或%)是通過重復(fù)兩次來逃脫的。對于格式語法,兩者都是{和}需要通過重復(fù)它們來逃脫。
$ python3 string_template.py TEMPLATE: Variable : foo Escape : $ Variable in text: fooiable INTERPOLATION: Variable : foo Escape : % Variable in text: fooiable FORMAT: Variable : foo Escape : {} Variable in text: fooiable
模板與字符串內(nèi)插或格式化之間的一個關(guān)鍵區(qū)別是,參數(shù)的類型沒有被考慮在內(nèi)。將值轉(zhuǎn)換為字符串,并將字符串插入到結(jié)果中。沒有可用的格式設(shè)置選項。例如,無法控制用于表示浮點值的數(shù)字數(shù)。
不過,有一個好處是,使用safe_substitute()方法可以避免異常,如果不是以參數(shù)形式提供模板所需的所有值。
#字符串模板丟失.py import string values = {'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.py ERROR: 'missing' safe_substitute(): foo is here but $missing is not provided
高級模板
string.Template可以通過調(diào)整用于在模板正文中查找變量名稱的正則表達式模式來更改。一個簡單的方法是更改delimiter和idpattern類屬性。
#字符串模板 import string class 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))
在本例中,替換規(guī)則被更改,因此分隔符是%而不是$變量名必須包括中間的下劃線。
模式%notunderscored不會被任何東西替換,因為它不包含下劃線字符。
$ python3 string_template_advanced.py Modified ID pattern: Delimiter : % Replaced : replaced Ignored : %notunderscored
對于更復(fù)雜的更改,可以重寫pattern屬性并定義一個全新的正則表達式。
提供的模式必須包含四個命名組,用于捕獲轉(zhuǎn)義分隔符、命名變量、變量名的大括號版本和無效分隔符模式。
#字符串模板_defaultpattern.py import string t = 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 )
此示例定義一個新模式以創(chuàng)建一種新類型的模板,使用{{var}}作為變量語法。
#字符串模板_newsyntax.py import re import string class 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模式都必須單獨提供,即使它們是相同的。運行示例程序?qū)⑸梢韵螺敵觯?br />
$ python3 string_template_newsyntax.py MATCHES: [('{{', '', '', ''), ('', 'var', '', '')] SUBSTITUTED: {{ replacement
格式化程序
這個Formatter類實現(xiàn)與format()方法str。它的功能包括類型強制、對齊、屬性和字段引用、命名和位置模板參數(shù)以及特定于類型的格式選項。大多數(shù)時候format()方法是這些特性的更方便的接口,但是Formatter作為構(gòu)建子類的一種方法,用于需要變體的情況下。
常數(shù)
這個string模塊包括一些與ASCII和數(shù)字字符集相關(guān)的常量。
#字符串常數(shù).py import inspect import string def is_str(value): return isinstance(value, str) for name, value in inspect.getmembers(string, is_str): if name.startswith('_'): continue print('%s=%r\n' % (name, value))
這些常量在處理ASCII數(shù)據(jù)時很有用,但是由于在某種形式的Unicode中遇到非ASCII文本越來越常見,因此它們的應(yīng)用受到限制。
$ python3 string_constants.py ascii_letters='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVW XYZ' ascii_lowercase='abcdefghijklmnopqrstuvwxyz' ascii_uppercase='ABCDEFGHIJKLMNOPQRSTUVWXYZ' digits='0123456789' hexdigits='0123456789abcdefABCDEF' octdigits='01234567' printable='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQ RSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' punctuation='!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' whitespace=' \t\n\r\x0b\x0c'
到此這篇關(guān)于詳解Python中string模塊除去Str還剩下什么的文章就介紹到這了,更多相關(guān)Python string模塊內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
打印tensorflow恢復(fù)模型中所有變量與操作節(jié)點方式
這篇文章主要介紹了打印tensorflow恢復(fù)模型中所有變量與操作節(jié)點方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05TensorFlow打印tensor值的實現(xiàn)方法
今天小編就為大家分享一篇TensorFlow打印tensor值的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07在Python中使用defaultdict初始化字典以及應(yīng)用方法
今天小編就為大家分享一篇在Python中使用defaultdict初始化字典以及應(yīng)用方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-10-10在PyCharm導(dǎo)航區(qū)中打開多個Project的關(guān)閉方法
今天小編就為大家分享一篇在PyCharm導(dǎo)航區(qū)中打開多個Project的關(guān)閉方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01