Python2.7-string模塊

string模塊html

一、模塊內定義的常數python

字母(ascii_letters、letters),數字(digits、hexdigits、octdigits),空格(whitespace),大小寫(ascii_lowercase、ascii_uppercase、lowercase、uppercase),標點符號(punctuation),前述中可打印的集合(printable)git

二、格式化字符串,基本與內置的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 能夠爲 「+」,「-」,「 」,分別表明爲全部數字添加符號,只爲負數添加符號,在正數前添加空格和爲負數添加符號
    # 在2、8、十六進制前分別添加「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」,「%」(將數字以百分制表示)函數

三、string模塊中的Template類spa

用$標識,與%和格式化相似
>>> from string import Template
>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'code

四、string模塊的另外一些方法orm

string.capwords(s [,sep])與str.title()類似,惟一區別在於能夠設置sep分割字符串
string.maketrans(from, to)與str.translate()相同htm

總結:
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() 將字符串變大小寫ip

相關文章
相關標籤/搜索