最近在看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