標籤:科學 sign pac 數字 har field 格式 art 去除
string模組
1、模組內定義的常數
字母(ascii_letters、letters),數字(digits、hexdigits、octdigits),空格(whitespace),大小寫(ascii_lowercase、ascii_uppercase、lowercase、uppercase),標點符號(punctuation),前述中可列印的集合(printable)
2、格式化字串,基本與內建的str類型功能相似,格式為 “{” [field_name] [“!” conversion] [“:” format_spec] “}”
field_name 為格式化處標誌名稱,可以省略
conversion 可以取值 r 或 s 分別代表用 repr() 與 str() 顯示
format_spec 格式為 [[fill]align][sign][#][0][width][,][.precision][type]
fill 為填充至 width 長度的任一字元
align 可以為 “<”,“>”,“=”,“^”,分別表示靠左對齊,靠右對齊,在數位符號與數字之間填充,置中對齊
sign 可以為 “+”,“-”,“ ”,分別代表為所有數字添加符號,只為負數添加符號,在正數前添加空格和為負數添加符號
# 在二、八、十六進位前分別添加“0b”,“0o”,“0x”
0 作用與 [fill] 設定為“0”或 [align] 設定為“=”相同
width 指定字串長度
, 將數字每三位加逗號
.precision 指定小數位元,不能對整數使用,對非數字使用時指定最大字元數
type 可以為“b”(二進位),“c”(數字轉unicode字元),“d”(十進位),“e”(科學計數法),“E”,“f”(預設6位小數),“F”,“g”(通用格式),“G”,“n”(同g),“o”(八進位),“s”(預設格式,字串),“x”(十六進位),“X”,“%”(將數字以百分製表示)
3、string模組中的Template類
用$標識,與%和格式化類似
>>> from string import Template
>>> s = Template(‘$who likes $what‘)
>>> s.substitute(who=‘tim‘, what=‘kung pao‘)
‘tim likes kung pao‘
4、string模組的另一些方法
string.capwords(s [,sep])與str.title()相似,唯一區別在於可以設定sep分割字串
string.maketrans(from, to)與str.translate()相同
總結:
string模組的功能與內建str類型的功能基本相同
補充一些常用str的函數:
str.count(sub [,start[,end]]) 統計sub在str中出現次數
str.endswith(suffix [,start[,end]]) 判斷str的結尾是否為suffix
str.startswith(prefix [,start[,end]]) 判斷str的開始是否為prefix
str.format(*args, **keargs) 格式化字串
str.strip([chars]) 從str的前後去除指定字元,預設為空白格,還有lstrip和rstrip方法
str.split([sep[,maxsplit]]) 返回用sep分割字串後的列表,最大分割maxsplit次
str.join(iterable) 將字串類型的iterable對象用str串連起來
str.upper().lower() 將字串變大小寫
Python2.7-string模組