前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python怎么对数字进行过滤

python怎么对数字进行过滤

作者头像
砸漏
发布2020-10-21 14:43:23
1K0
发布2020-10-21 14:43:23
举报
文章被收录于专栏:恩蓝脚本

本文实例总结了Python实现简易过滤删除数字的方法。分享给大家供大家参考,具体如下:

如果想从一个含有数字,汉字,字母的列表中滤除仅含有数字的字符,当然可以采取正则表达式来完成,但是有点太麻烦了,因此可以采用一个比较巧妙的方式:

1、正则表达式解决

代码语言:javascript
复制
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、巧妙地避开正则表达式

代码语言:javascript
复制
L = [ 'xiaohong', '12', 'adf12', '14',u'晓明']
for x in L:
 try:
  int(x)
 except:
  print x

3、使用string内置方法

代码语言:javascript
复制
L = [ 'xiaohong', '12', 'adf12', '14',u'晓明']
#对于python3来说同样还可以使用string.isnumeric()方法
for x in L:
 if not x.isdigit():
  print x

4、去除两端的数字

如果只是去除两端可能含有数字的字符串里的数字,则可以使用内置的strip,方式如下:

代码语言:javascript
复制
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) 中,不需要有序,切记!

实例扩展:

代码语言:javascript
复制
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如何过滤数字内容请搜索ZaLou.Cn以前的文章或继续浏览下面的相关文章希望大家以后多多支持ZaLou.Cn!

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-09-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档