python怎么對(duì)數(shù)字進(jìn)行過濾
本文實(shí)例總結(jié)了Python實(shí)現(xiàn)簡(jiǎn)易過濾刪除數(shù)字的方法。分享給大家供大家參考,具體如下:
如果想從一個(gè)含有數(shù)字,漢字,字母的列表中濾除僅含有數(shù)字的字符,當(dāng)然可以采取正則表達(dá)式來(lái)完成,但是有點(diǎn)太麻煩了,因此可以采用一個(gè)比較巧妙的方式:
1、正則表達(dá)式解決
import reL = [u’小明’, ’xiaohong’, ’12’, ’adf12’, ’14’]for i in range(len(L)): if re.findall(r’^[^d]w+’,L[i]): print re.findall(r’^w+$’,L[i])[0] elif isinstance(L[i],unicode): print L[I]
2、巧妙地避開正則表達(dá)式
L = [ ’xiaohong’, ’12’, ’adf12’, ’14’,u’曉明’]for x in L: try: int(x) except: print x
3、使用string內(nèi)置方法
L = [ ’xiaohong’, ’12’, ’adf12’, ’14’,u’曉明’]#對(duì)于python3來(lái)說(shuō)同樣還可以使用string.isnumeric()方法for x in L: if not x.isdigit(): print x
4、去除兩端的數(shù)字
如果只是去除兩端可能含有數(shù)字的字符串里的數(shù)字,則可以使用內(nèi)置的strip,方式如下:
In [24]: import stringIn [25]: astring = ’12313213215just for 32 test 1306436’In [26]: astring.strip(string.digits)Out[26]: ’just for 32 test ’In [27]: astring.rstrip(string.digits)Out[27]: ’12313213215just for 32 test ’In [30]: astring.lstrip(string.digits)Out[30]: ’just for 32 test 1306436’#注意In [31]: astringOut[31]: ’12313213215just for 32 test 1306436’In [32]: astring.strip(’0123456’)Out[32]: ’just for 32 test ’
.strip([char]) 中的 char 給定時(shí),則截取兩端的字符直到滿足不在set(char) 中,不需要有序,切記!
實(shí)例擴(kuò)展:
crazystring = ’dade142.!0142f[., ]ad’# 只保留數(shù)字new_crazy = filter(str.isdigit, crazystring)print(’’.join(list(new_crazy))) #輸出:1420142# 只保留字母new_crazy = filter(str.isalpha, crazystring)print(’’.join(list(new_crazy))) #睡出:dadefad# 只保留字母和數(shù)字new_crazy = filter(str.isalnum, crazystring)print(’’.join(list(new_crazy))) #輸出:dade1420142fad# 如果想保留數(shù)字0-9和小數(shù)點(diǎn)’.’ 則需要自定義函數(shù)new_crazy = filter(lambda ch: ch in ’0123456789.’, crazystring)print(’’.join(list(new_crazy))) #輸出:142.0142.
上述代碼運(yùn)行結(jié)果:
1420142dadefaddade1420142fad142.0142.
到此這篇關(guān)于python怎么對(duì)數(shù)字進(jìn)行過濾的文章就介紹到這了,更多相關(guān)python如何過濾數(shù)字內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 詳解瀏覽器的緩存機(jī)制2. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)3. ASP基礎(chǔ)知識(shí)VBScript基本元素講解4. UDDI FAQs5. XML入門的常見問題(四)6. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)7. XML解析錯(cuò)誤:未組織好 的解決辦法8. asp(vbscript)中自定義函數(shù)的默認(rèn)參數(shù)實(shí)現(xiàn)代碼9. 利用CSS3新特性創(chuàng)建透明邊框三角10. 使用Spry輕松將XML數(shù)據(jù)顯示到HTML頁(yè)的方法
