Python的字符串處理,在爬蟲的數據解析、大數據的文本清洗,以及普通文件處理等方面應用非常廣泛,而且Python對字符串的處理內置了很多高效的函數,功能非常強大、使用非常方便。今天我就把字符串處理時用到最多的方法總結分享給大家,希望大家可以輕松應對字符串處理。
1.字符串的切片和相乘
(1)切片
str='Monday is a busy day' print(str[0:7]) #表示取第一個到第七個的字符串 print(str[-3:]) #表示取從倒數第三個字符開始到結尾的字符串 print(str[::]) #復制字符串
(2)相乘
當我們編寫Python代碼時要分隔符,此時用字符串的乘法操作就很容易實現。
line='*'*30 print(line) >>******************************
2.字符串的分割
(1)普通的分割,用split函數,但是split只能做非常簡單的分割,而且不支持多個分隔。
phone='400-800-800-1234' print(phone.split('-')) >>['400', '800', '800', '1234']
(2)復雜的分割,r表示不轉義,分隔符可以是「;」,或者「,」,或者空格后面跟0個多個額外的空格,然后按照這個模式去分割。
line='hello world; python, I ,like, it' import re print(re.split(r'[;,s]\s*',line)) >>>['hello world', 'python', 'I ', 'like', 'it']
3.字符串的連接和合并
(1)連接,兩個字符可以很方便的通過“+”連接起來
str1='Hello' str2='World' new_str=str1+str2 print(new_str) >>>HelloWorld
(2)合并,用join方法
url=['www','python','org'] print('.'.join(url)) >>>www.python.org
4.判斷字符串是否以指定前綴、后綴結尾
假設我們要查一個文件的名字是以什么開頭或者什么結尾?
filename='trace.h' print(filename.endswith('h')) >>True print(filename.startswith('trace')) >>True
5.字符串的查找和匹配
(1)一般查找
利用find方法可以很方便的在長的字符串里面查找子字符串,會返回字符串所在位置的索引,若找不到返回-1
str1 = "this is string example....wow!!!" str2 = "exam" print(str1.find(str2)) # 15 print(str1.find(str2, 10)) # 15 print(str1.find(str2, 40)) # -1
(2)復雜的匹配,就需要用到正則表達式。
mydate='11/27/2016' import re if re.match(r'\d+/\d+/\d+',mydate): print('ok.match') else: print('not match') >>>ok.match
6.統計字符串里某個字符出現的次數
str = "thing example....wow!!!" print(str.count('i', 0, 5)) # 1 print(str.count('e')) # 2
7.字符串的替換
(1)普通的替換,用replace方法就可以了
text='python is an easy to learn,powerful programming language.' print(text.replace('learn','study')) >>>python is an easy to study,powerful programming language.
(2)復雜的替換,需要用到re模塊的sub函數
students='Boy 103,girl 105' import re print(re.sub(r'\d+','100',students)) >>>Boy 100,girl 100
8.去掉字符串中一些特定的字符
(1)去空格,對文本處理的時候比如從文件中讀取一行,然后需要去除每一行的空格、table或者是換行符。
str = ' python str ' print(str) # 去首尾空格 print(str.strip()) # 去左側空格 print(str.lstrip()) # 去右側空格 print(str.rstrip())
(2)復雜的文本清理,可以利用str.translate。
比如先構建一個轉換表,table是一個翻譯表,表示把“to”轉成大寫的“TO”,然后在old_str里面去掉‘12345',然后剩下的字符串再經過table翻譯。
instr = 'to' outstr = 'TO' old_str = 'Hello world , welcome to use Python. 123456' remove = '12345' table = str.maketrans(instr,outstr,remove) new_str = old_str.translate(table) print(new_str) >>>HellO wOrld , welcOme TO use PyThOn. 6
總結
平時我們使用Python都是處理一些腳本,其中使用頻率最大的就是字符串的處理方面,因此給大家整理了這些常用的字符串處理時使用的方法,希望對大家有用。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
