這篇文章將為大家詳細(xì)講解有關(guān)python怎樣去除字符串頭尾的多余符號(hào),小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
在讀文件時(shí)常常得到一些\n和引號(hào)之類的符號(hào),可以使用字符串的成員函數(shù)strip()來去除。
1.去除首尾不需要的字符
a= '"This is test string"' # strip()會(huì)默認(rèn)去除'\n','\r','\t',' ',制表回車換行和空格等字符 a.strip('"') >>> 'This is test string' b = ' This is another string ' #首尾兩個(gè)空格 b.strip(' ') >>>'This is another string' b.strip() >>>'This is another string' # 默認(rèn)去除 c = '*This is an-another string/' # 首尾兩個(gè)字符 c.strip('*/') #這里strip將解析每一個(gè)字符,檢查首尾是否存在,存在就去除返回 >>>'This is an-another string' d = '//This is the last string**' d.strip('*/') >>> d = 'This is the last string' # 持續(xù)去除首尾的指定字符符號(hào) e = 'einstance' e.strip('e') # 去除首尾特定字符 >>> 'instanc'
2.去除末尾特定字符
專治末尾多余字符rstrip()
a = ' example ' a.rstrip() #同樣默認(rèn)去除末尾的空格\n,\t,\r >>>' example' b = 'this is mya' b.rstrip('a') #去除末尾特定字符 >>>'this is my'
3.去除開頭特定字符
專治開頭多余字符lstrip()
a = ' example ' a.lstrip() #默認(rèn)去除開頭的空格\n,\t,\r >>>'example ' b = 'athis is mya' b.lstrip('a') #去除末尾特定字符 >>>'this is mya'
4.去除字符串中的特定字符
一種常見的方法是轉(zhuǎn)換為list,再使用remove方法,隨后再轉(zhuǎn)換為string,這里再額外說明兩種方法。使用replace()和re.sub()
# 使用字符串replace()方法,將目標(biāo)字符替換為空 a = 'this is the test' a.replace('t','') >>>'his is he es' #第二種方法使用正則表達(dá)式方法 import re re.sub('s','', a) >>>'thi i the tet'
5.巧用eval()函數(shù)
eval函數(shù)的作用是將傳入的字符串作為表達(dá)式來進(jìn)行計(jì)算,可以有效去除(雙)引號(hào),空格等字符。
a = ' "This is a good example" ' eval(a) >>>`This is a good example` b = ' "This is a good example" ' eval(b) >>>'This is a good example'
重要提示:字符串外面的引號(hào)和字符串內(nèi)的引號(hào)不能同時(shí)使用單引號(hào)或雙引號(hào),外面用了單引號(hào)里面只能用雙引號(hào),否則會(huì)引起異常。
關(guān)于“python怎樣去除字符串頭尾的多余符號(hào)”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。
本文標(biāo)題:python怎樣去除字符串頭尾的多余符號(hào)-創(chuàng)新互聯(lián)
本文URL:http://chinadenli.net/article44/ddihee.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供動(dòng)態(tài)網(wǎng)站、商城網(wǎng)站、靜態(tài)網(wǎng)站、網(wǎng)站設(shè)計(jì)公司、服務(wù)器托管、App設(shè)計(jì)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容