最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python 如何去除字符串頭尾的多余符號

 更新時間:2019年11月19日 13:47:02   作者:hitrjj  
這篇文章主要介紹了python 如何去除字符串頭尾的多余符號,在python開發(fā)中經(jīng)常會遇到這樣的需求,今天小編通過實例代碼給大家講解,需要的朋友可以參考下

在讀文件時常常得到一些\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)文章

最新評論

汝城县| 商洛市| 齐齐哈尔市| 温宿县| 禹城市| 米脂县| 通城县| 济宁市| 高陵县| 长治市| 依安县| 江孜县| 探索| 鹤山市| 安乡县| 徐汇区| 蒙自县| 罗平县| 安国市| 宜昌市| 新和县| 安新县| 临颍县| 青海省| 石狮市| 筠连县| 准格尔旗| 二连浩特市| 体育| 灵武市| 健康| 扎兰屯市| 湘潭县| 汕头市| 鄄城县| 吴江市| 邢台县| 苏尼特左旗| 福鼎市| 黑山县| 汝南县|