Python实现简易过滤删除数字的方法小结

yipeiwu_com6年前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) 中,不需要有序,切记!

以下分别是python2和python3中string的方法:

PS:这里再为大家提供2款非常方便的正则表达式工具供大家参考使用:

JavaScript正则表达式在线测试工具:
http://tools.jb51.net/regex/javascript

正则表达式在线生成工具:
http://tools.jb51.net/regex/create_reg

更多关于Python相关内容可查看本站专题:《Python正则表达式用法总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

python各种语言间时间的转化实现代码

一 基本知识 millisecond 毫秒 microsecond 微秒 nanosecond 纳秒 1秒=1000毫秒 1毫秒=1000微秒 1微秒=1000纳秒 二 perl pe...

python判断一个集合是否包含了另外一个集合中所有项的方法

本文实例讲述了python判断一个集合是否包含了另外一个集合中所有项的方法。分享给大家供大家参考。具体如下: >>> L1 = [1, 2, 3, 3] >&...

selenium使用chrome浏览器测试(附chromedriver与chrome的对应关系表)

selenium使用chrome浏览器测试(附chromedriver与chrome的对应关系表)

使用WebDriver在Chrome浏览器上进行测试时,需要从http://chromedriver.storage.googleapis.com/index.html网址中下载与本机c...

视频合并时使用python批量修改文件名的方法

视频合并时使用python批量修改文件名的方法

不知道大家有没有遇到这样的情况,比如视频合并时文件名没有按照正常顺序排列,像这样    可见,文件名排序是乱的。这个样子合并出来的视频一定也是乱的。所以得想办法把文件...

python给微信好友定时推送消息的示例

如下所示: from __future__ import unicode_literals from threading import Timer from wxpy import...