詳解Python中string模塊除去Str還剩下什么
string模塊可以追溯到早期版本的Python。以前在本模塊中實(shí)現(xiàn)的許多功能已經(jīng)轉(zhuǎn)移到str物品。這個(gè)string模塊保留了幾個(gè)有用的常量和類來處理str物品。
字符串-文本常量和模板
目的:包含用于處理文本的常量和類。
功能
功能capwords()將字符串中的所有單詞大寫。字符串capwords.py
import strings = ’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.pyThe 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)。或者,如果需要的話,也可以用花括號(hào)(例如,${var}).此示例使用%運(yùn)算符和新的格式字符串語法。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))
在前兩種情況下,觸發(fā)器字符($或%)是通過重復(fù)兩次來逃脫的。對于格式語法,兩者都是{和}需要通過重復(fù)它們來逃脫。
$ python3 string_template.pyTEMPLATE:Variable : fooEscape : $Variable in text: fooiableINTERPOLATION:Variable : fooEscape : %Variable in text: fooiableFORMAT:Variable : fooEscape : {}Variable in text: fooiable
模板與字符串內(nèi)插或格式化之間的一個(gè)關(guān)鍵區(qū)別是,參數(shù)的類型沒有被考慮在內(nèi)。將值轉(zhuǎn)換為字符串,并將字符串插入到結(jié)果中。沒有可用的格式設(shè)置選項(xiàng)。例如,無法控制用于表示浮點(diǎn)值的數(shù)字?jǐn)?shù)。
不過,有一個(gè)好處是,使用safe_substitute()方法可以避免異常,如果不是以參數(shù)形式提供模板所需的所有值。
#字符串模板丟失.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))
因?yàn)闆]有價(jià)值missing在值字典中,KeyError是由substitute()。
而不是提高錯(cuò)誤,safe_substitute()捕獲它并將變量表達(dá)式單獨(dú)保留在文本中。
$ python3 string_template_missing.pyERROR: ’missing’safe_substitute(): foo is here but $missing is not provided
高級(jí)模板
string.Template可以通過調(diào)整用于在模板正文中查找變量名稱的正則表達(dá)式模式來更改。一個(gè)簡單的方法是更改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))
在本例中,替換規(guī)則被更改,因此分隔符是%而不是$變量名必須包括中間的下劃線。
模式%notunderscored不會(huì)被任何東西替換,因?yàn)樗话聞澗€字符。
$ python3 string_template_advanced.pyModified ID pattern: Delimiter : % Replaced : replaced Ignored : %notunderscored
對于更復(fù)雜的更改,可以重寫pattern屬性并定義一個(gè)全新的正則表達(dá)式。
提供的模式必須包含四個(gè)命名組,用于捕獲轉(zhuǎn)義分隔符、命名變量、變量名的大括號(hào)版本和無效分隔符模式。
#字符串模板_defaultpattern.pyimport stringt = string.Template(’$var’)print(t.pattern.pattern)
價(jià)值t.pattern是已編譯的正則表達(dá)式,但原始字符串可通過其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)
此示例定義一個(gè)新模式以創(chuàng)建一種新類型的模板,使用{{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模式都必須單獨(dú)提供,即使它們是相同的。運(yùn)行示例程序?qū)⑸梢韵螺敵觯?/p>
$ python3 string_template_newsyntax.pyMATCHES: [(’{{’, ’’, ’’, ’’), (’’, ’var’, ’’, ’’)]SUBSTITUTED:{{replacement
格式化程序
這個(gè)Formatter類實(shí)現(xiàn)與format()方法str。它的功能包括類型強(qiáng)制、對齊、屬性和字段引用、命名和位置模板參數(shù)以及特定于類型的格式選項(xiàng)。大多數(shù)時(shí)候format()方法是這些特性的更方便的接口,但是Formatter作為構(gòu)建子類的一種方法,用于需要變體的情況下。
常數(shù)
這個(gè)string模塊包括一些與ASCII和數(shù)字字符集相關(guān)的常量。
#字符串常數(shù).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數(shù)據(jù)時(shí)很有用,但是由于在某種形式的Unicode中遇到非ASCII文本越來越常見,因此它們的應(yīng)用受到限制。
$ python3 string_constants.pyascii_letters=’abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’ascii_lowercase=’abcdefghijklmnopqrstuvwxyz’ascii_uppercase=’ABCDEFGHIJKLMNOPQRSTUVWXYZ’digits=’0123456789’hexdigits=’0123456789abcdefABCDEF’octdigits=’01234567’printable=’0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!'#$%&’()*+,-./:;<=>?@[]^_`{|}~ tnrx0bx0c’punctuation=’!'#$%&’()*+,-./:;<=>?@[]^_`{|}~’whitespace=’ tnrx0bx0c’
到此這篇關(guān)于詳解Python中string模塊除去Str還剩下什么的文章就介紹到這了,更多相關(guān)Python string模塊內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. html中的form不提交(排除)某些input 原創(chuàng)2. ASP動(dòng)態(tài)網(wǎng)頁制作技術(shù)經(jīng)驗(yàn)分享3. vue使用moment如何將時(shí)間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時(shí)間格式4. jsp文件下載功能實(shí)現(xiàn)代碼5. 開發(fā)效率翻倍的Web API使用技巧6. ASP常用日期格式化函數(shù) FormatDate()7. js select支持手動(dòng)輸入功能實(shí)現(xiàn)代碼8. CSS3中Transition屬性詳解以及示例分享9. asp.net core項(xiàng)目授權(quán)流程詳解10. CSS3實(shí)現(xiàn)動(dòng)態(tài)翻牌效果 仿百度貼吧3D翻牌一次動(dòng)畫特效
