歡迎您光臨本站 註冊首頁

python怎麼對數字進行過濾

←手機掃碼閱讀     f2h0b53ohn @ 2020-07-06 , reply:0

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

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

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內置方法

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

 

4、去除兩端的數字

如果只是去除兩端可能含有數字的字符串裡的數字,則可以使用內置的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'  # 只保留數字  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.


                                                     

   


[f2h0b53ohn ] python怎麼對數字進行過濾已經有245次圍觀

http://coctec.com/docs/python/shhow-post-241484.html