Python 標準庫筆記: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

    Ingored : %notunderscored


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


4.常用字符串技巧


  • 1.反轉字符串


>>> s = '1234567890'

>>> print s[::-1]

0987654321


  • 2.關於字符串鏈接


儘量使用join()鏈接字符串,因爲’+’號連接n個字符串需要申請n-1次內存,使用join()需要申請1次內存。


  • 3.固定長度分割字符串


>>> import re

>>> s = '1234567890'

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章