溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Python字符串處理的8招秘籍(小結)

發布時間:2020-09-10 09:45:34 來源:腳本之家 閱讀:153 作者:googpy 欄目:開發技術

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都是處理一些腳本,其中使用頻率最大的就是字符串的處理方面,因此給大家整理了這些常用的字符串處理時使用的方法,希望對大家有用。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女