本文實例總結了Python實現簡易過濾刪除數字的方法。分享給大家供大家參考,具體如下:
如果想從一個含有數字,漢字,字母的列表中濾除僅含有數字的字符,當然可以采取正則表達式來完成,但是有點太麻煩了,因此可以采用一個比較巧妙的方式:
1、正則表達式解決
1
2
3
4
5
6
7
|
import re L = [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、巧妙地避開正則表達式
1
2
3
4
5
6
|
L = [ 'xiaohong' , '12' , 'adf12' , '14' ,u '曉明' ] for x in L: try : int (x) except : print x |
3、使用string內置方法
1
2
3
4
5
|
L = [ 'xiaohong' , '12' , 'adf12' , '14' ,u '曉明' ] #對于python3來說同樣還可以使用string.isnumeric()方法 for x in L: if not x.isdigit(): print x |
4、去除兩端的數字
如果只是去除兩端可能含有數字的字符串里的數字,則可以使用內置的strip,方式如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
In [ 24 ]: import string In [ 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 ]: astring Out[ 31 ]: '12313213215just for 32 test 1306436' In [ 32 ]: astring.strip( '0123456' ) Out[ 32 ]: 'just for 32 test ' |
.strip([char]) 中的 char 給定時,則截取兩端的字符直到滿足不在set(char) 中,不需要有序,切記!
實例擴展:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
crazystring = 'dade142.!0142f[., ]ad' # 只保留數字 new_crazy = filter ( str .isdigit, crazystring) print (''.join( list (new_crazy))) #輸出:1420142 # 只保留字母 new_crazy = filter ( str .isalpha, crazystring) print (''.join( list (new_crazy))) #睡出:dadefad # 只保留字母和數字 new_crazy = filter ( str .isalnum, crazystring) print (''.join( list (new_crazy))) #輸出:dade1420142fad # 如果想保留數字0-9和小數點'.' 則需要自定義函數 new_crazy = filter ( lambda ch: ch in '0123456789.' , crazystring) print (''.join( list (new_crazy))) #輸出:142.0142. |
上述代碼運行結果:
1420142
dadefad
dade1420142fad
142.0142.
到此這篇關于python怎么對數字進行過濾的文章就介紹到這了,更多相關python如何過濾數字內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://www.py.cn/faq/python/14313.html