Python標準庫 一

2021-07-24 22:37:35 字數 1647 閱讀 6325

首先介紹文字

python中關於文字的模組的常見函式的使用,模板替換的方式:

# coding=utf-8

#string模組保留了很多有用的常量和類用來處理string和unicode物件

#首先string中的capwords()將乙個字串中的所有單詞的首字母大寫

import string

s='the quick brown fox jumped over the lazy dog.'

print s

print string.capwords(s)

#maketrans()函式將建立轉換表,結合translate()使用將一組字元修改為另一組字元

leet=string.maketrans('abeguloprstz','463611092572') #每乙個字元都要替換成對應的字元

s='the quick brown fox jumped over the lazy dog.'

print s

print s.translate(leet)

#字串模板成為了替代內建拼接語法的一種候選方法,使用string.template拼接是,$來標記變數,${}來作為中間變數拼接

#$和%都是作為觸發器字元,都應該書寫2次完成轉義

values=

t=string.template("""

variable : $var

escape : $$

variable in text : $iable

""")

print

"template :",t.substitute(values)

s="""

variable : %(var)s

escape : %%

variable in text : %(var)siable

"""print

"template:",s % values

#注意當字典中不存在要替換的變數時,substitute會丟擲keyerror的異常,safe_substitute不會丟擲異常,他會捕獲異常並且將不被替換的字串原樣輸出

values=

t=string.template("$var is here but $missing is not provided")

print

"safe_substitute:",t.safe_substitute(values)

#通過修改string.template的預設語法,從而定義查詢變數的正規表示式的使用模式

template_text='''

delimiter : %%

replaced : %with_underscore

ignored : %noteunderscored

'''d=

class

mytemplate

(string.template):

delimiter = '%'

idpattern = '[a-z]+_[a-z]+'

t=mytemplate(template_text)

print

'modified id pattern:'

print t.safe_substitute(d)

python標準庫 時間庫

眾所皆知,每乙個程式語言都有自己的時間類庫,python也不例外用法十分簡單 最基本的類,time類 time基本函式介紹 import time print time.asctime 如果未傳入乙個tuple或乙個time struct就是使用當前的時間,返回乙個24字長的時間字串 就這個mon ...

python標準庫 os庫

os模組主要用於跟作業系統打交道 os模組常用的方法 os.getcwd 獲取當前工作目錄,即當前python指令碼工作的目錄路徑 os.chdir dirname 改變當前指令碼工作目錄 相當於shell下cd os.curdir 返回當前目錄 os.pardir 獲取當前目錄的父目錄字串名 os...

不屬於python標準庫 Python標準庫概覽

總結 這個部分講了一些常用的python庫的方法。一下子也記不住,不過基本都自己敲了 試了試。os模組 os模組介紹了一些作業系統級別的方法 os.getcwd 得到當前工作目錄 os.chdir 改變工作目錄 os.system mkdir haha 建立資料夾haha 字串正則匹配 匯入re模組...