python怎么對數(shù)字進行過濾
本文實例總結(jié)了Python實現(xiàn)簡易過濾刪除數(shù)字的方法。分享給大家供大家參考,具體如下:
如果想從一個含有數(shù)字,漢字,字母的列表中濾除僅含有數(shù)字的字符,當(dāng)然可以采取正則表達式來完成,但是有點太麻煩了,因此可以采用一個比較巧妙的方式:
1、正則表達式解決
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、巧妙地避開正則表達式
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'曉明'] #對于python3來說同樣還可以使用string.isnumeric()方法 for x in L: if not x.isdigit(): print x
4、去除兩端的數(shù)字
如果只是去除兩端可能含有數(shù)字的字符串里的數(shù)字,則可以使用內(nèi)置的strip,方式如下:
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) 中,不需要有序,切記!
實例擴展:
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ù)點'.' 則需要自定義函數(shù) new_crazy = filter(lambda ch: ch in '0123456789.', crazystring) print(''.join(list(new_crazy))) #輸出:142.0142.
上述代碼運行結(jié)果:
1420142
dadefad
dade1420142fad
142.0142.
到此這篇關(guān)于python怎么對數(shù)字進行過濾的文章就介紹到這了,更多相關(guān)python如何過濾數(shù)字內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python連接數(shù)據(jù)庫使用matplotlib畫柱形圖
這篇文章主要介紹了Python連接數(shù)據(jù)庫使用matplotlib畫柱形圖,文章通過實例展開對主題的相關(guān)介紹。具有一定的知識參考價值性,感興趣的小伙伴可以參考一下2022-06-06python多進程執(zhí)行方法apply_async使用說明
這篇文章主要介紹了python多進程執(zhí)行方法apply_async使用說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03解決python和pycharm安裝gmpy2 出現(xiàn)ERROR的問題
這篇文章主要介紹了python和pycharm安裝gmpy2 出現(xiàn)ERROR的解決方法,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-08-08PyCharm 2021.2 (Professional)調(diào)試遠程服務(wù)器程序的操作技巧
本文給大家分享用 PyCharm 2021 調(diào)試遠程服務(wù)器程序的過程,通過圖文并茂的形式給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2021-08-08