Python常用的字串處理函式

2021-07-10 22:13:50 字數 2042 閱讀 1302

1. 

capitalize():

將字串中的第乙個字元大寫,需要注意的是,只有字串的首字元為字母時才能起到大寫作用

2. 

upper():

將字串全部轉成大寫;     lower(): 將字串全部轉成小寫; casefold(): 同lower()

3. 

title():  

將每個單詞的首字母變成大寫; istitle(): 判斷是否title模式;  isupper():判斷是否全大寫; islower():判斷是否全小寫; isalnum():判斷是否包含數字或者字母中的一種;  isalpha():判斷是否只包含字母一種;   isdigit(),isnumeric(), isdecimal(): 判斷是否是數字(包含.的浮點字串會返回false); isspace(): 判斷是否全空格;

4. 

center(width)

,ljust(width),rjust(width) 三個對齊字串的操作函式,分別是中間對齊,左對齊,右對齊;如果當width小於等於字串長度,則直接生成乙個與原字串一樣的字串,否則將會得到乙個長度為width,原字串在中間,左側或右側,其餘為空格的新字串。

5. 

zfill(width):

可以是字串右對齊並將0插入到字串左側得到乙個字串長度為width新字串。

6. 

strip([chars])

,引數為空時刪除字串前後空格,引數不為空時,刪除字串前後與引數一樣的字元, lstrip([chars])和rstrip([chars])分別刪除左邊,右邊的引數或空格;

7. 

find(sub[,start[,end]])

和index(sub[,start[,end]]): 都是判斷sub子字串是否包含在字串內,包含則返回對應的索引值,不一樣的地方在於,如果不包含,前者會返回-1,而後者則報錯 (預設從左邊開始查詢); 對應的有rfind(sub[,start[,edd]])和rindex(sub[,start[,edd]]);

8. 

endswith(sub[,start[,end]])

和startswith(prefix[,start[,end]]):分別判斷字串首或尾部是否以子字串開頭;

9. 

partition(sub)

和rpartition(sub)將字串分為三個元組(字串sub左邊的,sub,字串sub右邊的);如果sub不在字串內,則返回為(原字串,'',''),不同的是,前者從字串左側開始查詢,後者從右側。

10.

expandtabs([tabsize=8]):

將字串中的/t轉變為空格,不輸入引數時轉變為8個,輸入引數時,轉變為引數多個;

11.

replace(old,new[,count]):

將字串中的old子字串替換為new子字串,如果count定義,則指定替換個數;

12.

count(sub[,start[,end]]):

統計sub子字串在字串中出現的次數,開始和結束位置不指定是為全部字串;

13.

split(sep=none,maxsplit=-1)  

將字串按照sep進行分割,預設分割次數maxsplit,小於0時為分割完全,否則按照指定次數分割,分割完後的子字串作為元素組成乙個列表返回;

14.

splitlines([keepends])

將字串以'\n'作為分割符,返回分割後子字串組成的列表,keepends指定時,如果keepends非0,則返回帶'\n'子字串,為0時,與不指定時相同;

Python的partition字串函式

rpartition s.rpartition sep head,sep,tail search for the separator sep in s,starting at the end of s,and return the part before it,the separator itsel...

python字串處理常用方法

1 str.find str.rfind str.index str.rindex str.count s hello python,hello world s.find hello 從左側開始查詢 0 s.rfind hello 從右側開始查詢 13 s.find wahaha 查詢失敗,返回 1...

Python 字串處理常用函式

python處理字串有很多常用函式 1.使用成員操作符in str hello,world n sstr n result sstr in str print result true2.使用字串的find index 火count 方法 str hello,world n sstr n result...