當前位置:
首頁 > 知識 > Python 標準庫筆記:string模塊

Python 標準庫筆記:string模塊

(點擊

上方藍字

,快速關注我們)




來源:j_hao104 


my.oschina.net/jhao104/blog/829775


如有好文章投稿,請點擊 → 這裡了解詳情





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




看完本文有收穫?請轉

發分享給更多人


關注「P

ython開發者」,提升Python技能


喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 Python開發者 的精彩文章:

Python 判斷文件是否存在的三種方法
Greenlet 詳解
最難面試題,你遇到過什麼樣的?
Python標準庫:itertools模塊

TAG:Python開發者 |