python中的字串處理

來源:互聯網
上載者:User

1.字串轉換

s.lower() 轉為小寫

s.upper() 轉為大寫

s.swapcase() 大寫轉為小寫,小寫轉為大寫

s.capitalize() 首字母大寫

轉換為int類型 string.atoi(s) 或者int(s)

轉換為float類型 string.atof(s) 或者float(s)

轉換為long類型 string.atol(s) 或者long(s)

2.尋找等操作

s.find(sub,[,start[,end]]) 返回首次出現的位置,找不到返回-1

s.rfind(sub,[,start[,end]]) 返回最後一次出現的位置,找不到返回-1

s.index(sub[,start[,end]]) 與find()功能類似,找不到則傳出ValueEerror

s.rindex(sub[,start[,end]]) 與rfind()功能類似,找不到則傳出ValueError

s.count(sub[,start[,end]]) 返回子串出現的次數

s.replace(old,new[,maxreplace]) 替換字串,指定maxreplace時,只替換前maxreplace個

s.strip(char) 刪除開始和結尾處的char

s.split([,seq[,maxsplit]]) 返回分割字串的列表

s.join([sep]) 連接字串

3.位置

s.ljust(width[,fillchar]) 靠左對齊

s.rjust(width[,fillchar]) 靠右對齊

s.center(width[,fillchar]) 置中

s.zfill(width) 左邊補零直到長度到width

4.格式化輸出

format可以改變字串的輸出形式,舉例為:

‘{0},{2},{1}’.format(‘a’,’b’,’c’)

這裡{0} {1} {2}分別指代’a’ ‘b’ ‘c’

也可以按照名稱來寫:

‘cordix:{x},{y}’.format(x=’1’,y=’2’)

字串的靠左對齊也可以用format

‘{:<10}’.format(“hello”) 靠左對齊,寬度為10

‘{:>10}’.format(“hello”) 靠右對齊,寬度為10

‘{:^10}’.format(“hello”) 置中,寬度為10

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.