每周一個 Python 模塊 | string

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

string 模塊可以追溯到最早的 Python 版本。先前在此模塊中實現的許多功能已移至 str 對象方法。string 模塊保留了幾個有用的常量和類來處理 str 對象。

函數 capwords()

直接看下面的事例:

import string

s = 'The quick brown fox jumped over the lazy dog.'

print(s)    # The quick brown fox jumped over the lazy dog.
print(string.capwords(s))   # The Quick Brown Fox Jumped Over The Lazy Dog.

模板

字符串模板作為 PEP 292 一部分添加,旨在替代內置插值語法。通過 string.Template 插值,在名稱前加上 $(例如,$var)來標識變量?;蛘撸绻枰獙⑺鼈儚闹車奈谋局性O置出來,它們也可以用花括號包裹(例如:${var})。

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))

# output
# TEMPLATE:
# Variable        : foo
# Escape          : $
# Variable in text: fooiable
# 
# INTERPOLATION:
# Variable        : foo
# Escape          : %
# Variable in text: fooiable
# 
# FORMAT:
# Variable        : foo
# Escape          : {}
# Variable in text: fooiable

在前兩種情況下,觸發(fā)字符($或%)通過重復兩次來轉義。對于語法格式,{} 都需要通過重復它們進行轉義。

模板和字符串插值或格式化之間的一個關鍵區(qū)別是不考慮參數類型。這些值將轉換為字符串,并將字符串插入到結果中,沒有可用的格式選項。例如,無法控制用于表示浮點值的位數。

有一個好處是,如果并非模板所需的所有值都作為參數提供,則使用 safe_substitute() 方法可以避免異常。

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))

# output
# ERROR: 'missing'
# safe_substitute(): foo is here but $missing is not provided

由于字典中沒有 missing 值,引發(fā)了一個 KeyError,safe_substitute() 捕獲它并在文本中單獨保留變量表達式。

高級模板

可以通過調整用于在模板主體中查找變量名稱的正則表達式模式來更改默認語法。一種簡單的方法是更改 delimiteridpattern 類屬性。

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))

# output
# Modified ID pattern:
# 
#   Delimiter : %
#   Replaced  : replaced
#   Ignored   : %notunderscored

在此示例中,替換規(guī)則已更改,以分隔符%代替,而變量名必須在中間某處包含下劃線。該模式 %notunderscored 不會被任何內容替換,因為它不包含下劃線字符。

對于更復雜的更改,可以覆蓋 pattern 屬性并定義全新的正則表達式。提供的模式必須包含四個命名組,用于捕獲轉義分隔符,命名變量,變量名稱的支撐版本以及無效分隔符模式。

import string

t = string.Template('$var')
print(t.pattern.pattern)

# output
# \$(?:
#   (?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
# )

t.pattern 是一個已編譯的正則表達式,但原始字符串可通過其 pattern 屬性獲得。

此示例使用 {{var}} 作為變量語法定義用于創(chuàng)建新類型模板的新模式。

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'))

# output
# MATCHES: [('{{', '', '', ''), ('', 'var', '', '')]
# SUBSTITUTED:
# {{
# replacement

無論是 namedbraced 模式必須單獨提供,即使它們是相同的。

常數

string 模塊包含許多與 ASCII 和數字字符集相關的常量。

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))
    
# output
# ascii_letters='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
# 
# 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'

這些常量在處理 ASCII 數據時很有用,但由于在某種形式的 Unicode 中遇到非 ASCII 文本越來越常見,因此它們的應用受到限制。

相關文檔:

https://pymotw.com/3/string/index.html

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • 官網 中文版本 好的網站 Content-type: text/htmlBASH Section: User ...
    不排版閱讀 4,711評論 0 5
  • python的re模塊--細說正則表達式 可能是東半球最詳細最全面的re教程,翻譯自官方文檔,因為官方文檔寫的是真...
    立而人閱讀 23,435評論 4 46
  • 秋夜風雨急 滾滾黃河浪 拔地上云天 此時得清閑
    曹廣潼樹根草閱讀 308評論 0 3
  • 應用及視圖的生命周期 應用生命周期 從點擊iOS屏幕的應用圖標啟動應用開始,到應用完全退出內存為止,期間的所有應用...
    揚揚揚閱讀 1,769評論 0 4
  • 時光久遠,走過歲月的山山水水,一念花落,一念花開。
    酒分閱讀 115評論 0 0

友情鏈接更多精彩內容