python怎么对数字进行过滤

本文实例总结了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.
到此这篇关于python怎么对数字进行过滤的文章就介绍到这了,更多相关python如何过滤数字内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
每日分享,喜欢的看标题和多多点赞收藏加关注~~蟹蟹
原文地址:https://www.cnblogs.com/nanhe/p/13709197.html