python中的字符串處理
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
python中的字符串處理