說明:模式(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()、groups或group(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
更多字符串操作詳細內容,請參考:https://docs.python.org/3/library/stdtypes.html#string-methods