詳解Python中string模塊除去Str還剩下什么
string模塊可以追溯到早期版本的Python。
以前在本模塊中實現的許多功能已經轉移到str物品。
這個string模塊保留了幾個有用的常量和類來處理str物品。
字符串-文本常量和模板
目的:包含用于處理文本的常量和類。
功能
功能capwords()將字符串中的所有單詞大寫。
字符串capwords.py
import string s = 'The quick brown fox jumped over the lazy dog.' print(s) print(string.capwords(s))
結果與調用split(),將結果列表中的單詞大寫,然后調用join()把結果結合起來。
$ python3 string_capwords.py The 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 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ā)器字符($或%)是通過重復兩次來逃脫的。對于格式語法,兩者都是{和}需要通過重復它們來逃脫。
$ 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
模板與字符串內插或格式化之間的一個關鍵區(qū)別是,參數的類型沒有被考慮在內。將值轉換為字符串,并將字符串插入到結果中。沒有可用的格式設置選項。例如,無法控制用于表示浮點值的數字數。
不過,有一個好處是,使用safe_substitute()方法可以避免異常,如果不是以參數形式提供模板所需的所有值。
#字符串模板丟失.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可以通過調整用于在模板正文中查找變量名稱的正則表達式模式來更改。一個簡單的方法是更改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
對于更復雜的更改,可以重寫pattern屬性并定義一個全新的正則表達式。
提供的模式必須包含四個命名組,用于捕獲轉義分隔符、命名變量、變量名的大括號版本和無效分隔符模式。
#字符串模板_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模式都必須單獨提供,即使它們是相同的。運行示例程序將生成以下輸出:
$ python3 string_template_newsyntax.py
MATCHES: [('{{', '', '', ''), ('', 'var', '', '')]
SUBSTITUTED:
{{
replacement
格式化程序
這個Formatter類實現與format()方法str。它的功能包括類型強制、對齊、屬性和字段引用、命名和位置模板參數以及特定于類型的格式選項。大多數時候format()方法是這些特性的更方便的接口,但是Formatter作為構建子類的一種方法,用于需要變體的情況下。
常數
這個string模塊包括一些與ASCII和數字字符集相關的常量。
#字符串常數.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數據時很有用,但是由于在某種形式的Unicode中遇到非ASCII文本越來越常見,因此它們的應用受到限制。
$ 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'
到此這篇關于詳解Python中string模塊除去Str還剩下什么的文章就介紹到這了,更多相關Python string模塊內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python語言中pandas字符串分割str.split()函數
分列在我們日常工作中經常用到,從各種系統(tǒng)中導出的什么訂單號、名稱、日期很多都是復合組成的,這些列在匹配、合并時沒有辦法使用,我們經常需要將她們分開,下面這篇文章主要給大家介紹了關于python語言中pandas字符串分割str.split()函數的相關資料,需要的朋友可以參考下2022-08-08
Pandas之使用drop_duplicates:去除重復項
這篇文章主要介紹了Pandas之使用drop_duplicates:去除重復項方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12
Python操作Sonqube API獲取檢測結果并打印過程解析
這篇文章主要介紹了Python操作Sonqube API獲取檢測結果并打印過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-11-11
用 Django 開發(fā)一個 Python Web API的方法步驟
這篇文章主要介紹了用 Django 開發(fā)一個 Python Web API的方法步驟,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-12-12

