python 字串操作方法

2021-08-09 06:05:28 字數 2351 閱讀 2267

字串物件的操作方法:序列操作方法(內建函式或表示式,如lenth(...))和型別特定方法(物件方法呼叫,如s.find(...))。

說明:模式(pattern)匹配是指正規表示式,re模組。而文字串分隔符就是簡單的字串。

字串分割:

str.split()  python內建函式,返回值為列表,只能傳入單一的文字串分隔符,如str.split(','),如果不傳參,將預設使用空白字元:換行符、空格、製表符

re.split(pattern,str)  需要匯入re模組,返回值為列表

另str.splitlines():

str.splitlines() 按照行('\r', '\r\n', \n')分隔,返回乙個包含各行作為元素的列表,如果引數為 false,不包含換行符,如果為 true,則保留換行符。

#!/usr/bin/python

str1 = 'ab c\n\nde fg\rkl\r\n'

print str1.splitlines();

str2 = 'ab c\n\nde fg\rkl\r\n'

print str2.splitlines(true)

以上例項輸出結果如下:

['ab c', '', 'de fg', 'kl']

['ab c\n', '\n', 'de fg\r', 'kl\r\n']

字串搜尋:

re.match(pattern,str)  返回的是match物件,通過obj.group()列印輸出。從str的開頭匹配,若要完全匹配,pattern要以$結尾。

re.search(pattern,str)  返回的是match物件,通過obj.group()列印輸出。從str的任意位置匹配。注意,如果string中存在多個pattern子串,只返回第乙個

re.findall(pattern,str)  返回值為列表, 匹配str的所有。

re.finditer(pattern, string[, flags])  返回string中所有與pattern相匹配的全部字串,返回形式為match物件的迭代器。

以上獲取匹配結果需要呼叫match物件的group()groupsgroup(index)方法,返回值為元祖

字串替換:

re.sub(pattern,'repacement',str) 返回值為替換後的字串

str.replace(『a 』,'all',5)  返回替換後的字串。3個引數,將str中的a空格(謹慎填寫)替換為all,一共替換5處。5可以省略,預設替換所有。

以下為python內建函式:

len(str)  計算字串包含字元的個數

split() 上面已經介紹過了

', '.join(list)  將列表list中的內容通過逗號和空格粘合在一起。

以下兩個方法,一般用於判斷檔案以什麼開頭或結尾:

str.startswith('all')  str是否以all開頭 (注意:多個匹配時引數使用元祖。)

str.endswith('that\'s all') str是否以that's all結尾 (注意:多個匹配時引數使用元祖。)

str.find('the')  返回str中第一次出現the的位置偏移量,即返回整數值

str.rfind('the')  返回str中最後一次出現the的位置偏移量,即返回整數值

str.count('the') 返回整數值,the在str中一共出現了多少次

str.isalnum()  返回布林值,str中的所有字元都是字母或數字嗎?

關鍵字end使用(python3可以使用):

print(i, end='')  #可以用於將結果輸出到同一行,或者在輸出的末尾新增不同的字元

print(i, end=',')

python2去掉換行方法,末尾加個逗號:print(i),

關鍵字sep使用:

>>> a=10;b=388;c=98

>>> print(a,b,c,sep='@')

10@388@98

更多字串操作詳細內容,請參考:

Python 字串操作方法

1.capitalize 把字串的第乙個字元改為大寫 2.casefold 把整個字串的所有字元改寫小寫 3.center width 將字串居中,並使用空格填充至長度width的新字串 4.count sub start end 返回sub在字串裡面出現的次數,start和end引數表示範圍,可選...

python字串操作方法

一 hello world hello oworld s1 hello world s3 hell oworld print s1,s3,end 二 hello world hello,world s1 hello world s2 n hello,world n print s1,s2,end 三...

字串操作方法

indexof 返回查詢某乙個字串第一次出現的下標 定義字串 string.indexof 要查詢的字串 從哪一下標開始 返回第一次出現的下標 slice 擷取字串兩個引數第乙個是開始的下標,第二個是結束的下標,如果第乙個引數是負數就是倒數下標。str.slice 開始的位置,結束的位置 split...