生活随笔
收集整理的這篇文章主要介紹了
strip函数
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
一、strip函數(shù)原型
聲明:s為字符串,rm為要刪除的字符序列
s.strip(rm)????????刪除s字符串中開頭、結(jié)尾處,位于rm刪除序列的字符
s.lstrip(rm)???????刪除s字符串中開頭處,位于?rm刪除序列的字符
s.rstrip(rm)??????刪除s字符串中結(jié)尾處,位于?rm刪除序列的字符
如下:?
| 1 2 3 4 5 6 7 8 | >>>?a='hheloooo?goooodbyyyye' >>>?a.strip('helo?') 'goooodbyyyy' >>>?a.strip('he') 'loooo?goooodbyyyy' >>>?a.strip('o') 'hheloooo?goooodbyyyye' >>> |
從首尾開始找.先從首位找到'h'在['h','e','l','o']內(nèi)把'h'去掉,發(fā)現(xiàn)第二個(gè)'h'依然還在['h','e','l','o']內(nèi)再次去掉'h',往后推,發(fā)現(xiàn)'e'還在['h','e','l','o']內(nèi),繼續(xù)去掉'e',同理一直往下推.
從尾部開始發(fā)現(xiàn)'e'在['h','e','l','o']內(nèi),去掉'e',再發(fā)現(xiàn)'y'不在['h','e','l','o']內(nèi),所以就停止了.
?
?
1,?當(dāng)rm為空時(shí),默認(rèn)刪除空白符(包括'\n', '\r',? '\t',? ' ')
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | >>>?a='????a\n\tbc' >>>?print?a ????a ???????bc >>>?a.strip() 'a\n\tbc' >>>?a='??abc' >>>?a.strip() 'abc' >>>?a='\n\tabc' >>>?a.strip() 'abc' >>>?a='abc\n\t' >>>?a.strip() 'abc' >>> |
2,這里的rm刪除序列是只要邊(開頭或結(jié)尾)上的字符在刪除序列內(nèi),就刪除掉
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | >>>?a='123abc' >>>?a.strip('21') '3abc' >>>?a.strip('12') '3abc' >>>?a.strip('1a') '23abc' >>>?a.strip(cb) Traceback?(most?recent?call?last): ?File?"<stdin>",?line?1,?in?<module> NameError:?name?'cb'?is?not?defined >>>?a.strip('cb') '123a' >>>?a.strip('bc') '123a' >>> |
二、split函數(shù)
split是分割函數(shù),將字符串分割成“字符”,保存在一個(gè)列表中。
| 1 2 3 | >>>?a='a?b?c?d' >>>?a.split() ['a',?'b',?'c',?'d'] |
默認(rèn)不帶參數(shù)為空格分割。之所以為雙引號的“字符”,因?yàn)閷?shí)際python沒有字符的。
| 1 2 3 | >>>?b='abc?efg?hij?kkj' >>>?b.split() ['abc',?'efg',?'hij',?'kkj'] |
還可以帶參數(shù)根據(jù)實(shí)際需求進(jìn)行分割
| 1 2 3 4 5 | >>>?c='name=ding|age=25|job=it' >>>?c.split('|') ['name=ding',?'age=25',?'job=it'] >>>?c.split('|')[0].split('=') ['name',?'ding'] |
還可以帶上數(shù)字參數(shù),表示“切幾刀”如:
?
| 1 2 3 4 5 6 7 8 9 10 11 | >>>?d='a?b?c?d?e' >>>?d.split('?',1)#以空格“切一刀”,就分成兩塊了 ['a',?'b?c?d?e'] >>>?d.split('?',2) ['a',?'b',?'c?d?e'] >>>?d.split('?',3) ['a',?'b',?'c',?'d?e'] >>>?d.split('?',-1)?#d.split('?')結(jié)果一樣 ['a',?'b',?'c',?'d',?'e'] >>>?d.split('?') ['a',?'b',?'c',?'d',?'e'] |
?
本文出自 “丁同學(xué)1990” 博客,請務(wù)必保留此出處http://dingtongxue1990.blog.51cto.com/4959501/1675499
總結(jié)
以上是生活随笔為你收集整理的strip函数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。