最近在看python標準庫這本書,第一感受很是厚,第二感受,裏面有不少原來不知道的東西,如今記下來跟你們分享一下。python
string類是python中最經常使用的文本處理工具,在python的標準庫中,有大量的工具,能夠幫助咱們完成高級文本處理。函數
import string s = 'The quick brown fox jumped over the lazy dog.' print s print string.capwords(s)
運行結果以下:工具
The quick brown fox jumped over the lazy dog.
The Quick Brown Fox Jumped Over The Lazy Dog.
至關於先調用split(),這會將結果列表中的各個單詞的首字母大寫,而後再調用join()合併結果。ui
import string leet = string.maketrans('abegiloprstz', '463611092572') s = 'The quick brown fox jumped over the lazy dog.' print s print s.translate(leet)
運行結果以下:spa
The quick brown fox jumped over the lazy dog.
Th3 qu1ck 620wn f0x jum93d 0v32 7h3 142y d06.
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
運行結果3d
TEMPLATE:
Variable : foo
Escape : $
Variable in text : fooiablecode
INTERPOLATION:
Variable : foo
Escape : %
Variable in text : fooiableblog