Python字符串處理的8招秘籍
Python的字符串處理,在爬蟲的數(shù)據(jù)解析、大數(shù)據(jù)的文本清洗,以及普通文件處理等方面應用非常廣泛,而且Python對字符串的處理內(nèi)置了很多高效的函數(shù),功能非常強大、使用非常方便。今天我就把字符串處理時用到最多的方法總結(jié)分享給大家,希望大家可以輕松應對字符串處理。
1.字符串的切片和相乘
(1)切片
- str='Monday is a busy day'
- print(str[0:7]) #表示取第一個到第七個的字符串
- print(str[-3:]) #表示取從倒數(shù)第三個字符開始到結(jié)尾的字符串
- print(str[::]) #復制字符串
(2)相乘
當我們編寫Python代碼時要分隔符,此時用字符串的乘法操作就很容易實現(xiàn)。
- line='*'*30
- print(line)
- >>******************************
2.字符串的分割
(1)普通的分割,用split函數(shù),但是split只能做非常簡單的分割,而且不支持多個分隔。
- phone='400-800-800-1234'
- print(phone.split('-'))
- >>['400', '800', '800', '1234']
(2)復雜的分割,r表示不轉(zhuǎn)義,分隔符可以是「;」,或者「,」,或者空格后面跟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.判斷字符串是否以指定前綴、后綴結(jié)尾
假設我們要查一個文件的名字是以什么開頭或者什么結(jié)尾?
- 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.統(tǒng)計字符串里某個字符出現(xiàn)的次數(shù)
- 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函數(shù)
- 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())
- # 去左側(cè)空格
- print(str.lstrip())
- # 去右側(cè)空格
- print(str.rstrip())
(2)復雜的文本清理,可以利用str.translate。
比如先構(gòu)建一個轉(zhuǎn)換表,table是一個翻譯表,表示把“to”轉(zhuǎn)成大寫的“TO”,然后在old_str里面去掉‘12345’,然后剩下的字符串再經(jīng)過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
總結(jié)
平時我們使用Python都是處理一些腳本,其中使用頻率最大的就是字符串的處理方面,因此給大家整理了這些常用的字符串處理時使用的方法,希望對大家有用。