天天看點

string 字元串中字元無效_Python「字元串」:string子產品除去Str還剩下什麼字元串-文本常量和模闆功能模闆進階模闆格式化程式常數capwords()——首字母大小寫maketrans()——建立轉換表文法參數傳回值執行個體首字母大寫(capwords) 和 建立轉換表(maketrans)互相作用

string子產品可以追溯到早期版本的Python。

以前在本子產品中實作的許多功能已經轉移到str物品。

這個string子產品保留了幾個有用的常量和類來處理str物品。

還有兩個函數未從 string 子產品移出:capwords() 和 maketrans()。

string 字元串中字元無效_Python「字元串」:string子產品除去Str還剩下什麼字元串-文本常量和模闆功能模闆進階模闆格式化程式常數capwords()——首字母大小寫maketrans()——建立轉換表文法參數傳回值執行個體首字母大寫(capwords) 和 建立轉換表(maketrans)互相作用

字元串-文本常量和模闆

目的:包含用于處理文本的常量和類。

功能

功能capwords()将字元串中的所有單詞大寫。

#字元串capwords.pyimport 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))
           

在前兩種情況下,觸發器字元($或%)是通過重複兩次來逃脫的。對于格式文法,兩者都是{和}需要通過重複它們來逃脫。

string 字元串中字元無效_Python「字元串」:string子產品除去Str還剩下什麼字元串-文本常量和模闆功能模闆進階模闆格式化程式常數capwords()——首字母大小寫maketrans()——建立轉換表文法參數傳回值執行個體首字母大寫(capwords) 和 建立轉換表(maketrans)互相作用
$ python3 string_template.pyTEMPLATE:Variable        : fooEscape          : $Variable in text: fooiableINTERPOLATION:Variable        : fooEscape          : %Variable in text: fooiableFORMAT:Variable        : fooEscape          : {}Variable in text: fooiable
           

模闆與字元串内插或格式化之間的一個關鍵差別是,參數的類型沒有被考慮在内。将值轉換為字元串,并将字元串插入到結果中。沒有可用的格式設定選項。例如,無法控制用于表示浮點值的數字數。

string 字元串中字元無效_Python「字元串」:string子產品除去Str還剩下什麼字元串-文本常量和模闆功能模闆進階模闆格式化程式常數capwords()——首字母大小寫maketrans()——建立轉換表文法參數傳回值執行個體首字母大寫(capwords) 和 建立轉換表(maketrans)互相作用

不過,有一個好處是,使用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$) |                # two delimiters  (?P[_a-z][_a-z0-9]*)    | # identifier  {(?P[_a-z][_a-z0-9]*)} | # braced identifier  (?P)                    # ill-formed delimiter exprs)
           

此示例定義一個新模式以建立一種新類型的模闆,使用{{var}}作為變量文法。

#字元串模闆_newsyntax.pyimport reimport stringclass MyTemplate(string.Template):    delimiter = '{{'    pattern = r'''    {{(?:    (?P{{)|    (?P[_a-z][_a-z0-9]*)}}|    (?P[_a-z][_a-z0-9]*)}}|    (?P)    )    '''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=%r' % (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!"#$%&'()*+,-./:;<=>?@[]^_`{|}~ x0bx0c'punctuation='!"#$%&'()*+,-./:;<=>?@[]^_`{|}~'whitespace=' x0bx0c'
           

capwords()——首字母大小寫

capwords(), 把字元串(string)中, 所有單詞的首字母大寫;

這個capwords()的使用形式,[,sep]是個可選項。

string.capwords(s[,sep])
           

這個函數首先會把參數(這個s一般是個字元串)用str.split() 分割成一個個單詞,再用str.capitalize()函數把每個單詞的首字母大寫,最後用str.join()函數将單詞組合起來,如果第二個可選參數“sep”為空或為none,多個空格會被一個空格代替,字元串開頭和結尾的空格将會被移除,另外,sep 這個參數是用來分割群組合字元串的,以下是例子。

import strings = 'The quick brown fox jumped over the lazy dog.'print s print string.capwords(s)print string.capwords(s,None)print string.capwords('abcabcabc','a')
           

結果:

The quick brown fox jumped over the lazy dog.The Quick Brown Fox Jumped Over The Lazy Dog.The Quick Brown Fox Jumped Over The Lazy Dog.aBcaBcaBc
           

函數定義:

def capwords(s, sep=None):        """capwords(s [,sep])  -> string        Split the argument into words using split, capitalize each        word using capitalize, and join the capitalized words using        join. If the optional second argument sep is absent or None,        runs of whitespace characters are replaced by a single space        and leading and trailing whitespace are removed, otherwise        sep is used to split and join the words.        """        return (sep or ' ').join(x.capitalize()) for x in s.split(sep))
           

maketrans()——建立轉換表

建立對照表, 然後使用translate()函數, 調用對照表, 把字元串(string)中的字元, 進行相應的替換。

文法

maketrans()方法文法:

str.maketrans(intab, outtab[,delchars])
           

參數

  • intab -- 字元串中要替代的字元組成的字元串。
  • outtab -- 相應的映射字元的字元串。
  • delchars – 可選參數,表示要删除的字元組成的字元串。

    傳回一個字元映射轉換表供 translate() 方法調用。本文不考慮

傳回值

傳回字元串轉換後生成的新字元串。

執行個體

以下執行個體展示了使用maketrans() 方法将所有元音字母轉換為指定的數字:

#!/usr/bin/python# -*- coding: UTF-8 -*- from string import maketrans   # 必須調用 maketrans 函數。 intab = "aeiou"outtab = "12345"trantab = maketrans(intab, outtab) str = "this is string example....wow!!!"print str.translate(trantab)
           

以上執行個體輸出結果如下:

th3s 3s str3ng 2x1mpl2....w4w!!!
           

首字母大寫(capwords) 和 建立轉換表(maketrans)互相作用

代碼:

# -*- coding: utf-8 -*- '''Created on [email protected]: C.L.Wang''' import string s = 'The quick brown fox jumped over the lazy dog.' leet = string.maketrans('abcdefg', '1234567') #leet 腦殘 if __name__ == '__main__':    print(s)    print(string.capwords(s)) #首字母大寫    print(s.translate(leet)) #轉換    pass