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

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

python怎么對數字進行過濾

瀏覽:127日期: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 編程
相關文章:
主站蜘蛛池模板: 晋宁县| 上虞市| 昌宁县| 吴川市| 文安县| 若羌县| 清水县| 乡城县| 弋阳县| 福泉市| 宽城| 珲春市| 曲松县| 界首市| 贵德县| 措勤县| 岳池县| 应城市| 普格县| 武平县| 望奎县| 七台河市| 安泽县| 深泽县| 新安县| 沾化县| 清涧县| 珲春市| 鹤峰县| 石渠县| 宁强县| 息烽县| 石柱| 庆元县| 新密市| 澄迈县| 汤原县| 绩溪县| 平安县| 龙南县| 西吉县|