Python2.7-string模組

來源:互聯網
上載者:User

標籤:科學   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模組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.