【python】去除字符串頭尾的多餘符號

在讀文件時常常得到一些\n和引號之類的符號,可以使用字符串的成員函數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'    # 持續去除首尾的指定字符符號

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.去除字符串中的特定字符

一種常見的方法是轉換爲list,再使用remove方法,隨後再轉換爲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()函數

eval函數的作用是將傳入的字符串作爲表達式來進行計算,可以有效去除(雙)引號,空格等字符。

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'

重要提示:字符串外面的引號和字符串內的引號不能同時使用單引號或雙引號,外面用了單引號裏面只能用雙引號,否則會引起異常。

ref:用法詳解, 詳解二eval, list2dict, ****python倒序讀取文件

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章