python 如何去除字符串頭尾的多余符號
在讀文件時常常得到一些\n和引號之類的符號,可以使用字符串的成員函數(shù)strip()來去除。
1.去除首尾不需要的字符
a= '"This is test string"' # strip()會默認去除'\n','\r','\t',' ',制表回車換行和空格等字符
a.strip('"')
>>> 'This is test string'
b = ' This is another string ' #首尾兩個空格
b.strip(' ')
>>>'This is another string'
b.strip()
>>>'This is another string' # 默認去除
c = '*This is an-another string/' # 首尾兩個字符
c.strip('*/') #這里strip將解析每一個字符,檢查首尾是否存在,存在就去除返回
>>>'This is an-another string'
d = '//This is the last string**'
d.strip('*/')
>>> d = 'This is the last string' # 持續(xù)去除首尾的指定字符符號
e = 'einstance'
e.strip('e') # 去除首尾特定字符
>>> 'instanc'
2.去除末尾特定字符
專治末尾多余字符rstrip()
a = ' example '
a.rstrip() #同樣默認去除末尾的空格\n,\t,\r
>>>' example'
b = 'this is mya'
b.rstrip('a') #去除末尾特定字符
>>>'this is my'
3.去除開頭特定字符
專治開頭多余字符lstrip()
a = ' example '
a.lstrip() #默認去除開頭的空格\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()方法,將目標字符替換為空
a = 'this is the test'
a.replace('t','')
>>>'his is he es'
#第二種方法使用正則表達式方法
import re
re.sub('s','', a)
>>>'thi i the tet'
5.巧用eval()函數(shù)
eval函數(shù)的作用是將傳入的字符串作為表達式來進行計算,可以有效去除(雙)引號,空格等字符。
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'
重要提示:字符串外面的引號和字符串內(nèi)的引號不能同時使用單引號或雙引號,外面用了單引號里面只能用雙引號,否則會引起異常。
總結(jié)
以上所述是小編給大家介紹的python 如何去除字符串頭尾的多余符號,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
相關(guān)文章
關(guān)于numpy.where()函數(shù) 返回值的解釋
今天小編就為大家分享一篇關(guān)于numpy.where()函數(shù) 返回值的解釋,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12
Pycharm 文件更改目錄后,執(zhí)行路徑未更新的解決方法
今天小編就為大家分享一篇Pycharm 文件更改目錄后,執(zhí)行路徑未更新的解決方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07
搭建?Selenium+Python開發(fā)環(huán)境詳細步驟
這篇文章主要介紹了搭建?Selenium+Python開發(fā)環(huán)境詳細步驟的相關(guān)資料,需要的朋友可以參考下2022-10-10

