天天看點

(轉)Python 标準庫筆記:string子產品

String子產品包含大量實用常量和類,以及一些過時的遺留功能,并還可用作字元串操作。

1. 常用方法

2.字元串常量

3.字元串模闆Template

通過string.Template可以為Python定制字元串的替換标準,下面是具體列子:

>>>from string import Template >>>s = Template('$who like $what') >>>print s.substitute(who='i', what='python') i like python >>>print s.safe_substitute(who='i') # 缺少key時不會抛錯 i like $what >>>Template('${who}LikePython').substitute(who='I') # 在字元串内時使用{} 'ILikePython'

Template還有更加進階的用法,可以通過繼承string.Template, 重寫變量delimiter(定界符)和idpattern(替換格式), 定制不同形式的模闆。

import string template_text = ''' Delimiter : $de Replaced : %with_underscore Ingored : %notunderscored ''' d = {'de': 'not replaced',      'with_underscore': 'replaced',      'notunderscored': 'not replaced'} class MyTemplate(string.Template):     # 重寫模闆 定界符(delimiter)為"%", 替換模式(idpattern)必須包含下劃線(_)     delimiter = '%'     idpattern = '[a-z]+_[a-z]+' print string.Template(template_text).safe_substitute(d)  # 采用原來的Template渲染 print MyTemplate(template_text).safe_substitute(d)  # 使用重寫後的MyTemplate渲染

輸出:

Delimiter : not replaced     Replaced : %with_underscore     Ingored : %notunderscored     Delimiter : $de     Replaced : replaced

原生的Template隻會渲染界定符為$的情況,重寫後的MyTemplate會渲染界定符為%且替換格式帶有下劃線的情況。

4.常用字元串技巧

1.反轉字元串

>>> s = '1234567890' >>> print s[::-1] 0987654321

2.關于字元串連結

盡量使用join()連結字元串,因為’+’号連接配接n個字元串需要申請n-1次記憶體,使用join()需要申請1次記憶體。

3.固定長度分割字元串

>>> import re >>> re.findall(r'.{1,3}', s)  # 已三個長度分割字元串 ['123', '456', '789', '0']

4.使用()括号生成字元串

sql = ('SELECT count() FROM table '        'WHERE id = "10" '        'GROUP BY sex') print sql SELECT count() FROM table WHERE id = "10" GROUP BY sex

5.将print的字元串寫到檔案

>>> print >> open("somefile.txt", "w+"), "Hello World"  # Hello World将寫入檔案somefile.txt

技術連結