国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

python怎么對數字進行過濾

瀏覽:101日期:2022-07-18 16:11:30

本文實例總結了Python實現簡易過濾刪除數字的方法。分享給大家供大家參考,具體如下:

如果想從一個含有數字,漢字,字母的列表中濾除僅含有數字的字符,當然可以采取正則表達式來完成,但是有點太麻煩了,因此可以采用一個比較巧妙的方式:

1、正則表達式解決

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、巧妙地避開正則表達式

L = [ ’xiaohong’, ’12’, ’adf12’, ’14’,u’曉明’]for x in L: try: int(x) except: print x

3、使用string內置方法

L = [ ’xiaohong’, ’12’, ’adf12’, ’14’,u’曉明’]#對于python3來說同樣還可以使用string.isnumeric()方法for x in L: if not x.isdigit(): print x

4、去除兩端的數字

如果只是去除兩端可能含有數字的字符串里的數字,則可以使用內置的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 給定時,則截取兩端的字符直到滿足不在set(char) 中,不需要有序,切記!

實例擴展:

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.

上述代碼運行結果:

1420142dadefaddade1420142fad142.0142.

到此這篇關于python怎么對數字進行過濾的文章就介紹到這了,更多相關python如何過濾數字內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 牙克石市| 雷山县| 将乐县| 上饶市| 武强县| 台中市| 宣汉县| 南康市| 贵州省| 安龙县| 水城县| 广东省| 苍梧县| 邹城市| 柘城县| 大埔县| 句容市| 金平| 五河县| 收藏| 灌阳县| 瓦房店市| 克东县| 伊宁县| 天台县| 汕头市| 天津市| 连江县| 忻城县| 嘉禾县| 东光县| 迁西县| 固原市| 康定县| 岳阳市| 赤城县| 绿春县| 沈阳市| 突泉县| 衡东县| 聂荣县|