python string 文本常量和模版

    最近在看python標準庫這本書,第一感受很是厚,第二感受,裏面有不少原來不知道的東西,如今記下來跟你們分享一下。python

    string類是python中最經常使用的文本處理工具,在python的標準庫中,有大量的工具,能夠幫助咱們完成高級文本處理。函數

  • capwords()是將一個字符串中的全部單詞的首字母大寫。
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

  • maketrans()函數將建立轉換表,能夠用來結合translate()方法將一組字符修改爲另外一組字符,這種方法比反覆調用replace()更爲高效
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.
  • 字符串模版是替代內置拼接(interpolation)的一種候選方法。使用string.Template拼接時,能夠在變量名前面加上前綴$來標識變量,或者若是須要與兩側的文本相區分,還可使用大括號將變量括起。
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

相關文章
相關標籤/搜索